最近在使用httpClient使用multipart/form-data请求,这个过程极为恶心人,一共重要的2点:
- 核心代码1:Boundary不要忘了设置,这个是分隔符(随机生成字符串就行),可以自己百度下.
- 核心代码2:ContentType记得设置,不然导致中文编码异常
public static String postHikOpenApiByForm(String urlMap,String: param) { CloseableHttpClient httpClient = getHttpsClient(); try { HttpPost httpPost = new HttpPost(url); //[核心代码1.1]boundary分隔符随机生成 String boundary = UUIDGenerator.generateUUIDWithOutSlash(); //[核心代码1.2]分割符号别忘了设置到头里面的content_type httpPost.addHeader(HTTP.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary); //[核心代码2.1] ContentType contentType = ContentType.create("multipart/form-data", StandardCharsets.UTF_8); MultipartEntityBuilder builder = MultipartEntityBuilder.create() .setCharset(StandardCharsets.UTF_8) //[核心代码1.3]这里别忘了设置分割符 .setBoundary(boundary) ; if (!CollectionUtils.isEmpty(param)) { //设置请求参数 for (String item : param.keySet()) { //[核心代码2.2]这里请勿使用httpclient自带的contentType builder.addTextBody(item,param.get(item).toString(),contentType); } } //构建请求实体 HttpEntity entity = builder.build(); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); int responCode = response.getStatusLine().getStatusCode(); String resultStr = EntityUtils.toString(response.getEntity(), "UTF-8"); if (SUCCESS==responCode) { return resultStr; } log.error("请求 失败,返回错误码:{},返回体:{}", response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity(), "UTF-8")); throw new BusinessException(ErrorCodeEnum.REQUEST_OPEN_API_EXCEPTION); } finally { try { httpClient.close(); } catch (Exception el) { log.error("httpClient 释放异常", el); } } }
有问题可以留言私信