標籤:web開發 httpclient4.3.x httpcomponents
在web開發中,我們經常需要類比post及get請求,現在網上比較多的是使用httpclient3.x,然而httpclient4.x已經發布好幾年了,而且4.x之後改名為HttpComponents,顯然是今後的趨勢.
Apache HttpComponents4.x中的HttpClient是一個很好的工具,它符合HTTP1.1規範,是基於HttpCore類包的實現。但是HttpComponents4.x較之前httpclient3.x的API變化比較大,已經分為HttpClient,HttpCore,HttpAsyncClient等多個組件,在類比post及get請求時的編碼也出現了較大的變化.
下面是httpclient4.3.4類比get請求的常式
public void requestGet(String urlWithParams) throws Exception { CloseableHttpClient httpclient = HttpClientBuilder.create().build(); //HttpGet httpget = new HttpGet("http://www.baidu.com/"); HttpGet httpget = new HttpGet(urlWithParams); //配置請求的逾時設定 RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(50) .setConnectTimeout(50) .setSocketTimeout(50).build(); httpget.setConfig(requestConfig); CloseableHttpResponse response = httpclient.execute(httpget); System.out.println("StatusCode -> " + response.getStatusLine().getStatusCode()); HttpEntity entity = response.getEntity(); String jsonStr = EntityUtils.toString(entity);//, "utf-8"); System.out.println(jsonStr); httpget.releaseConnection();}
httpclient4.3.4類比post請求的常式
public void requestPost(String url,List<NameValuePair> params) throws ClientProtocolException, IOException { CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpPost httppost = new HttpPost(url); httppost.setEntity(new UrlEncodedFormEntity(params)); CloseableHttpResponse response = httpclient.execute(httppost); System.out.println(response.toString()); HttpEntity entity = response.getEntity(); String jsonStr = EntityUtils.toString(entity, "utf-8"); System.out.println(jsonStr); httppost.releaseConnection();}
運行post方法時,可以
public static void main(String[] args){ try { String loginUrl = "http://localhost:8080/yours"; List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", "zhang")); params.add(new BasicNameValuePair("passwd", "123")); requestPost(loginUrl,params); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }}
最後給出httpcomponents官網的常式
http://hc.apache.org/httpcomponents-core-4.3.x/examples.html