HttpClient如何发送文件呢?
下文笔者讲述HttpClient发送文件的方法分享,如下所示
实现思路: 将fileBody对象借助MultipartEntityBuilder对象 进入传入,即可实现发送文件的效果例:
public static String postFile(String url,String file,FileBody fileBody,Map<String,String> headers,Map<String,String> param) throws Exception { CloseableHttpClient httpClient = getHttpClient(); HttpPost post = new HttpPost(url); //设置请求头 for (String key : headers.keySet()) { post.setHeader(key, headers.get(key)); } //设置参数 MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for(Map.Entry<String, String> key : param.entrySet()){ builder.addTextBody(key.getKey(),key.getValue()); } //添加文件 builder.addPart(file,fileBody); HttpEntity reqEntity = builder.build(); post.setEntity(reqEntity); //发送请求 CloseableHttpResponse response = httpClient.execute(post); //获取响应 String respStr = null; HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { respStr = EntityUtils.toString(responseEntity, "UTF-8"); } //释放连接 EntityUtils.consume(response.getEntity()); response.close(); return respStr; }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。