转载请注明出处:
项目中有遇到http使用formData请求传输文件,在此记录一下
// 定义httpClient和response CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; try { // 创建默认的httpClient实例 SSLConnectionSocketFactory sslSf = createDefault(); httpClient = HttpClients.custom().setSSLSocketFactory(sslSf).build(); // 定义Post请求 HttpPost httpPost = new HttpPost(uri); // 设置配置 Builder builder = createBuilder(); RequestConfig config = null; // 是否开启代理模式访问 if (enabled) { HttpHost proxy = new HttpHost(host, port, Proxy.Type.HTTP.toString()); config = builder.setProxy(proxy).build(); } else { config = builder.build(); } httpPost.setConfig(config); // 设置请求头 // httpPost.setHeader(FucdnStrConstant.ACCEPT.getConstant(), MediaType.MULTIPART_FORM_DATA_VALUE); httpPost.setHeader(FucdnStrConstant.CONTENT_TYPE.getConstant(), MediaType.MULTIPART_FORM_DATA_VALUE); // 发送请求得到返回数据 httpPost.setEntity(fileBuilder.build()); // 得到响应 response = httpClient.execute(httpPost); // 状态码 int statusCode = response.getStatusLine().getStatusCode(); // 响应内容 HttpEntity entity = response.getEntity(); // 响应内容 String responseContent = EntityUtils.toString(entity); } catch (Exception e) { throw new FucdnException(e); } finally { // 关闭流 Utils.closeStream(response); Utils.closeStream(httpClient); }
原文:https://www.cnblogs.com/zjdxr-up/p/10864799.html