java – 如何发送POST请求并获取文件响应?
发布时间:2020-12-15 02:52:59 所属栏目:Java 来源:网络整理
导读:我想发送POST请求(如html表单)和获取文件(HTTP标题:“Content-Disposition:attachment; filename =”myfile.pdf“).你能帮助我吗? 解决方法 您最好的选择可能是使用第三方库,例如 HttpClient或 HTMLUnit. 如果您更喜欢使用标准API,那就不那么复杂了. // C
我想发送POST请求(如html表单)和获取文件(HTTP标题:“Content-Disposition:attachment; filename =”myfile.pdf“).你能帮助我吗?
解决方法
您最好的选择可能是使用第三方库,例如
HttpClient或
HTMLUnit.
如果您更喜欢使用标准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(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |