如何使用 JSoup 发布文件? [英] How to post files using JSoup?

查看:62
本文介绍了如何使用 JSoup 发布文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I`m using the following code post values using JSoup:

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

现在我也想提交一个文件.就像一个带有文件字段的表单.这可能吗 ?如果比如何?

And now I want to submit a file, too. Like a form with a file field. Is this possible ? If is than how ?

推荐答案

仅从 Jsoup 1.8.2 (Apr 13, 2015) 开始支持通过新的 data(String, String, InputStream) 方法.

This is only supported since Jsoup 1.8.2 (Apr 13, 2015) via the new data(String, String, InputStream) method.

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() 方法.

In older versions, sending multipart/form-data requests is not supported. Your best bet is using a fullworthy HTTP client for this, such as Apache HttpComponents Client. You can ultimately get the HTTP client response as String so that you can feed it to Jsoup#parse() method.

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 发布文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆