如何使用JSoup发布文件?
我使用JSoup使用以下代码发布值:
Document document = Jsoup.connect("http://www......com/....php") .data("user","user","password","12345","email","info@tutorialswindow.com") .method(Method.POST) .execute() .parse();
现在我也想提交一份文件。 就像带有文件字段的表单一样。 这可能吗 ? 如果比怎么样?
这仅在Jsoup 1。8。2(2015年4月13日)之后通过新data(String, String, InputStream)
方法得到支持。
String url = "http://www......com/....php"; File file = new File("/path/to/file.ext"); Document document = Jsoup.connect(url) .data("user", "user") .data("password", "12345") .data("email", "info@tutorialswindow.com") .data("file", file.getName(), new FileInputStream(file)) .post(); // ...
在旧版本中,不支持发送multipart/form-data
请求。 您最好的选择是使用一个完整的HTTP客户端,例如Apache HttpComponents Client 。 您最终可以将HTTP客户端响应作为String
获取,以便您可以将其提供给Jsoup#parse()
方法。
String url = "http://www......com/....php"; File file = new File("/path/to/file.ext"); MultipartEntity entity = new MultipartEntity(); entity.addPart("user", new StringBody("user")); entity.addPart("password", new StringBody("12345")); entity.addPart("email", new StringBody("info@tutorialswindow.com")); entity.addPart("file", new InputStreamBody(new FileInputStream(file), file.getName())); HttpPost post = new HttpPost(url); post.setEntity(entity); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); String html = EntityUtils.toString(response.getEntity()); Document document = Jsoup.parse(html, url); // ...
接受的答案在编写时起作用并且是正确的,但从那时起JSoup已经发展, 从版本1.8.2开始,可以将文件作为多部分表单的一部分发送 :
File file1 = new File("/path/to/file"); FileInputStream fs1 = new FileInputStream(file1); Connection.Response response = Jsoup.connect("http://www......com/....php") .data("user","user","password","12345","email","info@tutorialswindow.com") .data("file1", "filename", fs1) .method(Method.POST) .execute();
这篇文章让我走上正确的道路,但我不得不调整发布的答案,以使我的用例工作。 这是我的代码:
FileInputStream fs = new FileInputStream(fileToSend); Connection conn = Jsoup.connect(baseUrl + authUrl) .data("username",username) .data("password",password); Document document = conn.post(); System.out.println("Login successfully! Session Cookie: " + conn.response().cookies()); System.out.println("Attempting to upload file..."); document = Jsoup.connect(baseUrl + uploadUrl) .data("file",fileToSend.getName(),fs) .cookies(conn.response().cookies()) .post();
基本区别在于我首先登录该站点,保留响应中的cookie( conn
),然后将其用于后续上传文件。
希望它可以帮助你们。
- 在运行时更改CommonsMultipartResolver的maxUploadSize
- Struts 2 convention插件 – 上传超过2 MB的文件
- 以混合forms上传Spring文件
- 使用HttpClient4在上传文件中设置标题“Content-Type”时出现问题
- IE 11:发送Multipart Form Data请求时出错:Stream意外结束
- Spring MVC – AngularJS – 文件上传 – org.apache.commons.fileupload.FileUploadException
- 写入服务器时出错
- 如何在不传输整个文件的情况下限制使用JavaScript(或Java)上载的文件的大小?
- 如何处理MaxUploadSizeExceededException