標籤:sci lsm ext ucs spm mft lua isa tap
Java開發中,經常會需要訪問網路資源,一般都是使用http協議去進行訪問。進行網路訪問最簡單的方式就是使用apache提供的HttpClients包。在該篇部落格中,我會來實現使用HttpClients來進行GET請求和POST請求。
下面是使用GET請求訪問"http://www.baidu.com"網站:
public void get() { CloseableHttpClient httpclient = HttpClients.createDefault(); try { // 建立httpget. HttpGet httpget = new HttpGet("http://www.baidu.com"); System.out.println("executing request " + httpget.getURI()); // 執行get請求. CloseableHttpResponse response = httpclient.execute(httpget); try { // 擷取響應實體 HttpEntity entity = response.getEntity(); // 列印響應狀態 System.out.println(response.getStatusLine()); if (entity != null) { // 列印響應內容 System.out.println("返回內容: " + EntityUtils.toString(entity)); } } finally { response.close(); } } catch (java.io.IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } finally { // 關閉串連,釋放資源 try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } }
這裡不對返回的資料進行處理,如果返回的是JSON,則需要解析。如果是HTML,則需要前端頁面顯示。執行以上代碼後,返回的結果如所示,表示請求成功:
下面的代碼同樣是對同一個url進行POST請求:
public void post() { // 建立預設的httpClient執行個體. CloseableHttpClient httpclient = HttpClients.createDefault(); // 建立httppost,也可以把參數放入url中 HttpPost httppost = new HttpPost("http://www.baidu.com"); // 建立參數隊列,以索引值對的形式儲存 List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("phone", "1")); UrlEncodedFormEntity uefEntity; try { uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); //POST請求可以通過以下的方式把參數放到body中 httppost.setEntity(uefEntity); System.out.println("executing request " + httppost.getURI()); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8")); } } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉串連,釋放資源 try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } }
POST請求與GET請求很大的一個不同是把請求參數放入body中,而不是直接放到url中。請求返回的結果如所示:
在熟練使用HttpClients後,如果其他系統也提供有RESTful的介面,則我們可以非常方便的調用了。
Java開發基礎——HttpClients與網路請求