【问题标题】:How to send POST request and get file response?如何发送 POST 请求并获取文件响应?
【发布时间】:2011-07-06 18:42:15
【问题描述】:

我想发送 POST 请求(如 html 表单)并获取文件(HTTP 标头:“Content-Disposition: attachment; filename="myfile.pdf")。你能帮帮我吗?

【问题讨论】:

  • 你确定你的意思是 Java 而不是 Javascript?
  • 问题太模糊了。请描述您的环境。它是基于浏览器的应用程序吗? Servlet 有问题吗?

标签: java post attachment http-post content-disposition


【解决方案1】:

查看HttpClient。有一个相当全面的教程here

【讨论】:

    【解决方案2】:

    您最好的选择可能是使用第三方库,例如 HttpClientHTMLUnit

    如果您更喜欢使用标准 API,它并不复杂。

    // Construct data
    String data = URLEncoder.encode("key1", "UTF-8") + "=" + 
                                    URLEncoder.encode("value1", "UTF-8");
    
    data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" +
                                    URLEncoder.encode("value2", "UTF-8");
    
    // Send data
    URL url = new URL("http://hostname:80/cgi");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();
    
    // Get the response
    BufferedReader rd = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
    
    String line;
    while ((line = rd.readLine()) != null) {
        // Process line...
    }
    wr.close();
    rd.close();
    

    【讨论】:

      猜你喜欢
      • 2019-02-23
      • 2011-12-21
      • 2020-07-29
      • 2014-07-13
      • 2011-03-03
      • 2020-11-19
      • 1970-01-01
      • 2012-09-13
      • 1970-01-01
      相关资源
      最近更新 更多