Java中如何用HttpClient发送包含文件和参数的HTTP请求?

如何使用 httpclient 发送带文件和参数的 http 请求?

问题描述:
用户希望通过 java 程序发送一个包含文件和参数的 http 请求,但尝试使用 hutool 框架时遇到困难。

解决方案:
hutool 的 httprequest 确实无法为 multipartformdata 的每一项单独设置 content-type 和其他属性标头。因此,建议使用 httpclient 框架来发送此类 http 请求:

  1. 导入依赖

    
        org.apache.httpcomponents
        httpclient
        4.5.13
    
  2. 创建 httprequest

    httppost request = new httppost("http://example.com/upload");
  3. 构造请求体

    multipartentitybuilder multipartentitybuilder = multipartentitybuilder.create();
    multipartentitybuilder.addpart("file", new filebody(new file("path/to/file.txt")));
    multipartentitybuilder.addpart("参数名1", new stringbody("参数值1"));
    multipartentitybuilder.addpart("参数名2", ne

    w stringbody("参数值2")); httpentity multiparthttpentity = multipartentitybuilder.build(); request.setentity(multiparthttpentity);
  4. 设置请求头

    request.setheader(httpheaders.content_type, multiparthttpentity.getcontenttype().getvalue());
  5. 执行请求

    CloseableHttpResponse response = HttpClientBuilder.create().build().execute(request);

通过使用 httpclient,可以轻松构造 multipartformdata 请求体并设置必要的请求头,从而发送带有文件和参数的 http 请求。