之前只设置了httpPost.addHeader("Content-Type", "application/json;charset=utf-8"); 这还不够,还需要额外的请求头的参数设置,代码如下
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;
}
}
相关依赖
<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