加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何使用JSoup发布文件?

发布时间:2020-12-14 16:44:18 所属栏目:Java 来源:网络整理
导读:我使用JSoup使用以下代码发布值: Document document = Jsoup.connect("http://www......com/....php") .data("user","user","password","12345","email","info@tutorialswindow.com") .method(Method.POST) .execute() .parse(); 现在我也想提交一个文件.像
我使用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);
// ...

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读