JAVA使用HttpClient发送带附件参数的HTTP请求

首先打开任意可以上传图片的网站,打开浏览器监控并上传附件,然后在network监控里面查看上传附件的请求,其中比较重要的部分如下:

headers:

其中最重要的就是:

Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryVOpk39LzlafPENf1

multipart:它会将表单的数据处理为一条消息,以标签为单元,用分隔符分开。既可以上传键值对,也可以上传文件。当上传的字段是文件时,会有Content-Type来表名文件类型;content-disposition,用来说明字段的一些信息;画线部分请看下图Request Payload 部分。

boundary:即定义此请求中多个请求参数之间的分隔符,通常以“--”开头,以复杂字符串作为分隔符,以免与请求参数内的内容混淆。请求体中多个参数之间必须用headers定义的分隔符号分隔开。

有了以上定义了以后再来看这个请求体,Query String Parameters中存放一般字符串类型的参数键值对,Request Payload中存放用分隔符分隔的文件参数。


用java代码实现这个上传请求无非是要设置请求头中的Content-Type和设置多个文件参数。

maven依赖:

            <dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.3</version>
		</dependency>
		<dependency>
		    <groupId>org.apache.httpcomponents</groupId>
		    <artifactId>httpmime</artifactId>
		    <version>4.5.3</version>
		</dependency>

java代码: 

public static String httpPost(String url, Map<String, String> params, Map<String, File> files) {
        //HttpPost请求实体
        HttpPost httpPost = new HttpPost(url);
        //使用工具类创建 httpClient
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse resp = null;
        String respondBody = null;
        try {
            //设置请求超时时间和 sockect 超时时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
            httpPost.setConfig(requestConfig);
            //附件参数需要用到的请求参数实体构造器
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

            if (!CollectionUtils.isEmpty(files)) {
                files.forEach((name, file) -> {
                    //附件参数,name对应请求参数的key值,file为文件
                    //添加文件参数,分隔符号会被自动设置,我们无须关注                     
                    multipartEntityBuilder.addBinaryBody(name,file);
                });
            }
            if (!CollectionUtils.isEmpty(params)) {
                params.forEach((key, value) -> {
                    //此处的字符串参数会被设置到请求体Query String Parameters中
                    multipartEntityBuilder.addTextBody(key, value);
                }); 
            }
            HttpEntity httpEntity = multipartEntityBuilder.build();
            //将请求参数放入 HttpPost 请求体中
            //使用 httpEntity 后 Content-Type会自动被设置成 multipart/form-data
            httpPost.setEntity(httpEntity);
            //执行发送post请求
            resp = client.execute(httpPost);
            //将返回结果转成String
            respondBody = EntityUtils.toString(resp.getEntity());
        } catch (IOException | ParseException e) {
            //日志信息及异常处理
            String msg = "执行HTTP响应时抛出异常,需要关注";
            WebUtils.log.error(msg, e);
            throw new OperationFailtureException(msg, e);
        } finally {
            if (resp != null) {
                try {
                    //关闭请求
                    resp.close();
                } catch (IOException e) {  
                    WebUtils.log.error("关闭HTTP响应时抛出异常,需要关注", e);
                }
            }
        }
        return respondBody;
    }

单元测试:

使用微信公众平台提供的上传附件接口测试

	@Test
	public void testHttpPostUploadFiles() {
        //请求地址
	    String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload";
        //String参数
	    Map<String, String> params = new HashMap<String, String>();
	    params.put("type", "image");
        //此处access_token参数需要微信平台实时提供
	    params.put("access_token", "17_CWdnR5Lt-cUARueS-7NhaEsLfDrdguism23ptyJfd_y_GRO46Qf2ogvV6XFjDQ0CJE8Ghd7PhENMwXbN6q13HJNJlV1gWn6wQAVuKtu2Sx3wsbq5Gs1q1KvyCUuHl3VqzuwkDacE_jCdWHyvXFGgABAQYZ");
        //文件参数,微信接口暂时只支持单个文件上传
	    Map<String, File> files = new HashMap<>();
        //请保证文件存在
	    files.put("media", new File("/data/attFile/SYSTEMADMINISTRATOR/MODULE_WECHAT/Permanent/WECHAT_CUSTOMER_MESSAGE_PICTURE.jpg"));
        //调用接口
	    String resp = WebUtils.httpPost(url, params, files);
	    System.out.println(resp);
	    assertNotNull(resp);
	}

输出结果:

{"type":"image","media_id":"zulEAVKceEbyMRQxVRGOAZAC2jM3A8bA-PkZwSdacFXgGtBR77LWJRZpjIEX7G_f","created_at":1546571114}
 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
可以使用HttpClient类来发送参数POST请求。以下是一个简单的示例代码: ``` import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://example.com/api/post"); StringEntity entity = new StringEntity("param1=value1&param2=value2"); httpPost.setEntity(entity); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); CloseableHttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); System.out.println(EntityUtils.toString(responseEntity)); response.close(); httpClient.close(); } } ``` 在上面的代码中,我们创建了一个`CloseableHttpClient`对象,并使用`HttpPost`类来发送POST请求,请求地址为`http://example.com/api/post`。我们使用`StringEntity`类来封装请求参数,并通过设置请求头来告诉服务器请求内容的类型。最后,我们使用`CloseableHttpResponse`对象获取服务器的响应,并通过`EntityUtils.toString`方法将响应内容转换为字符串。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值