如何使用JSoup发布文件?

2022-09-03 12:27:18

我使用以下代码发布值与 JSoup:

Document document = Jsoup.connect("http://www......com/....php")
                    .data("user","user","password","12345","email","info@tutorialswindow.com")
                    .method(Method.POST)
                    .execute()
                    .parse();

现在我也想提交一个文件。类似于带有文件字段的表单。这可能吗?如果是比如何?


答案 1

自 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();
// ...

在旧版本中,不支持发送请求。你最好的选择是使用一个完全值得的HTTP客户端,比如Apache HttpComponents Client。您最终可以获得HTTP客户端响应,以便可以将其提供给Jsoup#parse()方法。multipart/form-dataString

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);
// ...

答案 2

接受的答案在撰写本文时是有效的,并且是正确的,但是从那时起,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();

推荐