我使用以下代码通过 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
请求。你最好的选择是为此使用完全有值(value)的 HTTP 客户端,例如 Apache HttpComponents Client .您最终可以获得作为 String
的 HTTP 客户端响应,以便您可以将其提供给 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);
// ...
关于java - 如何使用 JSoup 发布文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7370771/