Httpclient與RestTemplate的比較(比httpClient更優雅的Restful URL訪問)
一、HttpClient
(一)HttpClient 客戶端
1、HttpClient 是 apache 的開源,需要引入兩個包:httpclient-4.2.4.jar 和 httpcore-4.2.2.jar。
/** * HttpClien 的客戶端訪問 */ private void httpClientVisit() { String clientResponse = ""; try { HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(mUrl); //不是表單數據提交,這邊使用 StringEntity 即可 //UrlEncodedFormEntity等都是 HttpEntity 接口的實現類 StringEntity entity = new StringEntity(mRequestXml, "UTF-8");//編碼 entity.setContentType("text/xml"); request.setEntity(entity); // 發送請求 HttpResponse response = client.execute(request); org.apache.http.HttpEntity httpEntity = response.getEntity(); if (httpEntity != null) { // EntityUtils.toString 如果不指定編碼,EntityUtils默認會使用ISO_8859_1進行編碼 clientResponse = EntityUtils.toString(httpEntity, "UTF-8");// 記得設置編碼或者如下 // clientResponse = new String(EntityUtils.toString(httpEntity).getBytes("ISO_8859_1"), "UTF-8"); } if (clientResponse == null || "".equals(clientResponse)) { System.err.println("clientResponse is null or empty."); } System.out.println(clientResponse); } catch (Exception e) { e.printStackTrace(); } }
(二)HttpClient 詳解
1、Post方式訪問
/** * post方式提交表單(模擬用戶登錄請求) */ public void postForm() { String url = "http://localhost:8080/Java_WS_Server/rest/surpolicy/sendXml"; // 創建默認的httpClient實例. HttpClient client = new DefaultHttpClient(); // 創建httppost HttpPost httppost = new HttpPost(url); // 創建參數隊列 List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("username", "admin")); formparams.add(new BasicNameValuePair("password", "123456")); UrlEncodedFormEntity uefEntity; try { uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); //編碼 httppost.setEntity(uefEntity); System.out.println("executing request " + httppost.getURI()); HttpResponse response = client.execute(httppost); Header[] headers = response.getAllHeaders(); for(int i=0; i<headers.length; i++){ System.out.println(headers[i].getName()); } try { HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println("--------------------------------------"); System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8")); //編碼 System.out.println("--------------------------------------"); } } finally { } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } }
2、Get方式訪問
/** * 發送 get請求 */ public void get() { try { HttpClient client = new DefaultHttpClient(); // 創建httpget. HttpGet httpget = new HttpGet("http://www.baidu.com/"); System.out.println("executing request " + httpget.getURI()); // 執行get請求. HttpResponse response = client.execute(httpget); try { // 獲取響應實體 HttpEntity entity = response.getEntity(); System.out.println("--------------------------------------"); // 打印響應狀態 System.out.println(response.getStatusLine()); if (entity != null) { // 打印響應內容長度 System.out.println("Response content length: " + entity.getContentLength()); // 打印響應內容 System.out.println("Response content: " + EntityUtils.toString(entity)); } System.out.println("------------------------------------"); } finally { } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally {} }
3、亂碼問題:
1)利用:UrlEncodedFormEntity等 entity 容器,實現發送內容的編碼:
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); //編碼
StringEntity entity = new StringEntity(mRequestXml, "UTF-8");//編碼
2、EntityUtils.toString()方法的轉碼,實現返回內容的編碼:
EntityUtils.toString 如果不指定編碼,EntityUtils默認會使用ISO_8859_1進行編碼
clientResponse = EntityUtils.toString(httpEntity, "UTF-8");// 記得設置編碼或者如下
clientResponse = new String(EntityUtils.toString(httpEntity).getBytes("ISO_8859_1"), "UTF-8");
二、RestTemplate
(一)RestTemplate 客戶端
1、RestTemplate 是Spring的封裝,需要spring的包 spring-web-3.0.7.RELEASE.jar
2、客戶端代碼:
/** * RestTemplate 客戶端訪問 */ private void RestTemplateVisit() { String returnXml = ""; // 核心返回結果報文字符串 try { //復雜構造函數的使用 SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setConnectTimeout(1000);// 設置超時 requestFactory.setReadTimeout(1000); //利用復雜構造器可以實現超時設置,內部實際實現為 HttpClient RestTemplate restTemplate = new RestTemplate(requestFactory); //設置HTTP請求頭信息,實現編碼等 HttpHeaders requestHeaders = new HttpHeaders(); // requestHeaders.set("Accept", "text/"); requestHeaders.set("Accept-Charset", "utf-8"); requestHeaders.set("Content-type", "text/xml; charset=utf-8");// 設置編碼 //利用容器實現數據封裝,發送 HttpEntity<String> entity = new HttpEntity<String>(mRequestXml, requestHeaders); returnXml = restTemplate.postForObject(mUrl, entity, String.class); // 轉碼原因:RestTemplate默認是使用org.springframework.http.converter.StringHttpMessageConverter來解析 // StringHttpMessageConverter 默認用的 ISO-8859-1來編碼的 returnXml = new String(returnXml.getBytes("ISO-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println("restTemplate客戶端訪問返回: \n" + returnXml); }
具體的參考這個博客:
http://blog.csdn.net/u012228718/article/details/42028951
Httpclient與RestTemplate的比較(比httpClient更優雅的Restful URL訪問)