CloseableHttpClient设置超时时间demo 未设置默认是2分钟
作者:互联网
# CloseableHttpClient设置超时时间demo 未设置默认是2分钟 import org.apache.http.HttpHeaders; import org.apache.http.client.config.RequestConfig; 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; # org.apache.httpcomponents:httpclient:4.5.5 # 方法执行代码 String content = this.toJson(map or object对象转json); CloseableHttpClient httpClient = HttpClients.createDefault(); StringEntity stringEntity = new StringEntity(content); HttpPost post = new HttpPost(callbackUrlPic); post.addHeader(HttpHeaders.CONTENT_TYPE, "application/json"); post.setEntity(stringEntity); //设置超时时间,未设置默认是2分钟 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(8000).setConnectTimeout(6000).build(); post.setConfig(requestConfig); CloseableHttpResponse response = httpClient.execute(post); String res = EntityUtils.toString(response.getEntity()); //返回值的处理 todo public static String toJson(Object obj) { try { ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(obj); } catch (Exception e) { logger.error("convert obj to json error. obj="+obj, e); } return null; }
标签:http,demo,CloseableHttpClient,obj,设置,org,apache,import,post 来源: https://www.cnblogs.com/oktokeep/p/16588058.html