標籤:att nts com bar 強迫症 nginx bsp link error:
可用的code
public static String doPost(String url, String params, String contentType) /*throws IOException */{ CloseableHttpClient client = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(httpSoTimeout).setConnectTimeout(connectionTimeout).build();//佈建要求和傳輸逾時時間 String strResult = null; try { HttpPost post = new HttpPost(url); post.setConfig(requestConfig); if (StringUtils.isNotBlank(contentType)) { post.setHeader("Content-Type", contentType); } StringEntity se = new StringEntity(params); post.setEntity(se); HttpResponse response = client.execute(post); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK && response.getEntity() != null){ HttpEntity entity = response.getEntity(); strResult = EntityUtils.toString(entity, "utf-8"); EntityUtils.consume(entity); } } catch (Exception e) { log.error("http post error:{} ", e.getMessage()); return null; } return strResult; }}
最近用到了HttpClient寫爬蟲,可能我有新版本強迫症,老是喜歡用新版本的東西(雖說新版本不一定好用),然後就用了HttpClient 4.3。HttpClient這貨和Lucene一樣,每個版本的API都變化很大,這有點讓人頭疼。就好比建立一個HttpClient對象吧,每一個版本的都不一樣,
3.X是這樣的
HttpClient httpClient=new DefaultHttpClient();
4.3是這樣的
CloseableHttpClient httpClient = HttpClients.createDefault();
當然,上面這些變化只不過是一些小變化,大家看看API大家就都會了。
我要講的是逾時設定,HttpClient有三種逾時設定,最近比較忙,沒時間具體歸納總結,以後再補上,我這裡就講一些最簡單最易用的逾時設定方法。
這是個3.X的逾時設定方法
HttpClient client = new HttpClient();client.setConnectionTimeout(30000); client.setTimeout(30000);
HttpClient httpClient= new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
4.X版本的逾時設定(4.3後已淘汰)
HttpClient httpClient=new DefaultHttpClient();httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,2000);//連線時間httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,2000);//資料轉送時間
4.3版本逾時設定
CloseableHttpClient httpClient = HttpClients.createDefault();HttpGet httpGet=new HttpGet("http://www.baidu.com");//HTTP Get請求(POST雷同)RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();//佈建要求和傳輸逾時時間httpGet.setConfig(requestConfig);httpClient.execute(httpGet);//執行請求
BTW,4.3版本不設定逾時的話,一旦伺服器沒有響應,等待時間N久(>24小時)。
org.apache.http.client.HttpClient; HttpClient 4.3逾時設定