maven
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
<scope>compile</scope>
</dependency>
请求头 content-type 类型 https://www.runoob.com/http/http-content-type.html
multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式
请求头 Accept代表发送端(客户端)希望接受的数据类型。
使用
public static String post(String url, String jsonstr, Map<String, String> heads) throws IOException {
String result = "";
CloseableHttpResponse httpResponse = null;
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
try {
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
httpClient = HttpClientBuilder.create().build();
String charset = "utf-8";
// 定义请求的参数
//URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build();
//httpGet = new HttpGet(uri);
// 创建Post请求
httpPost = new HttpPost(url);
//解析对象
StringEntity entity = new StringEntity(jsonstr, charset);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
if (heads != null) {
for (String headKey : heads.keySet()) {
httpPost.setHeader(headKey, heads.get(headKey));
}
}
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(1000) //连接超时时间
.setConnectionRequestTimeout(1000) //从连接池中取的连接的最长时间
.setSocketTimeout(10 *1000) //数据传输的超时时间
.build();
httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(httpResponse.getEntity(), charset);
}
result = httpResponse.toString();
}finally {
if(httpResponse != null){
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
if(httpPost != null){
httpPost.clone();
}
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
if(httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
配置API RequestConfig()