HttpClient The current request is not a multipart request
报错的原因是因为,后台有文件上传,需要使用 multipart 的请求去完成。
一般post Body 写法 是这样写的,但是 httpClient 底层去请求的时候 还是用的
Content-Type:
application/json;charset=UTF-8 去执行的。 httpClient 专门提供了一个 multipart 请求的Entity,是 MultipartEntityBuilder。
创建方式是MultipartEntityBuilder builder = MultipartEntityBuilder.create();
需要自己去手动的设置一下 ContentType 的字符集,要不然的话 httplient 使用自己的字符集是 IOS-889.
ContentType strContent=ContentType.create("text/plain",Charset.forName("UTF-8"));
设置自己的字符集。
与一般的相比,已经用红框框出来了。
建议:当一个请求不通的时候,最好自己设置一个代理 看下请求到底是怎么走的,是自己参数没传。还是传的方式不对。还是传了后台没有接口。参数接收不成功。第一:客户端没有传。第二,传的方式不对。第三,后台没有接收。
贴一下完整的代码:
public static String httpPost(String url, Map<String, String> requestParams, String token) throws Exception {
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
ContentType strContent=ContentType.create("text/plain",Charset.forName("UTF-8"));
for (String key : requestParams.keySet()) {
builder.addTextBody(key, requestParams.get(key),strContent);
}
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
try {
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity, "utf-8");
EntityUtils.consume(httpEntity);
} finally {
if (httpResponse != null) {
httpResponse.close();
}
}
return result;
}
pom.xml文件
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-cache</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
<exclusions>
<exclusion>
<artifactId>commons-codec</artifactId>
<groupId>commons-codec</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>