之前只設(shè)置了httpPost.addHeader("Content-Type", "application/json;charset=utf-8"); 這還不夠,還需要額外的請求頭的參數(shù)設(shè)置,代碼如下
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.nio.charset.Charset;
public class HttpUtils {
public static String sendHttpPost(String url, String JSONBody) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(JSONBody.toString(), Charset.forName("UTF-8")));
CloseableHttpResponse response = httpClient.execute(httpPost);
// System.out.println(response.getStatusLine().getStatusCode() + "\n");
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, "UTF-8");
// System.out.println(responseContent);
response.close();
httpClient.close();
return responseContent;
}
}
相關(guān)依賴
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
參考資料來源:
https://blog.csdn.net/shuchongqu/article/details/88948589
https://www.cnblogs.com/soundcode/p/6560947.html