Java開發基礎——HttpClients與網路請求

來源:互聯網
上載者:User

標籤: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與網路請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.