報錯的原因是因爲,後臺有文件上傳,需要使用 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>