public static String doPostWithJSON(String url, String json) throws Exception { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type","application/json;charset=UTF-8"); StringEntity se = new StringEntity(json, Charset.forName("UTF-8")); se.setContentType("application/json"); httpPost.setEntity(se); CloseableHttpResponse response = client.execute(httpPost); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, "UTF-8"); return result; }
嗯,坑爹的地方来了,这个玩意发送请求,没设置超时时间,只要不响应,他能一直在这等着,这谁能受得了。
我要加个超时时间。
第二个大坑来了。
我记得以前设置超时时间是这样的。
client.setConnectionTimeout(10000); client.setTimeout(10000);
我发现,特么没这个方法。
于是查阅资料。发现HttpClient太善变了。每个版本都变api。
4.3版本是这样的
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,10000); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,10000);
4.3以后是这样的。
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build(); httpGet.setConfig(requestConfig);