Java使用HttpClient庫發送請求

HttpClient介紹

HttpClient是Apache Jakarta Common下的子項目,用來提供高效的、最新的、功能豐富的支持HTTP協議的客戶端編程工具包,並且它支持HTTP協議最新的版本和建議。HttpClient已經應用在很多的項目中,比如Apache Jakarta上很著名的另外兩個開源項目Cactus和HTMLUnit都使用了HttpClient。

下載和安裝

下載地址
http://hc.apache.org/downloads.cgi

下載二進制文件後解壓lib文件夾,將jar包複製粘貼到項目目錄,右擊add to Build Path.
關聯源碼到httpcomponents-asyncclient-4.1.1-src\httpcomponents-asyncclient-4.1.1\目錄即可查看源碼。

使用示例

    public static void post() {
        // 創建HttpClient實例對象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 創建Post請求
        HttpPost httppost = new HttpPost(
                "http://localhost:8080/服務端/servlet/Login");

        // 創建參數列表
        List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
        formparams.add(new BasicNameValuePair("user", "lisi"));
        formparams.add(new BasicNameValuePair("pwd", "123456"));

        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");

            // 設置廉潔配置
            httppost.setEntity(uefEntity);
            System.out.println("executing request " + httppost.getURI());

            // 執行連接操作
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {

                    // 遍歷Header
                    Header[] allHeaders = response.getAllHeaders();
                    for (Header h : allHeaders) {
                        System.out
                                .println(h.getName() + "  :  " + h.getValue());
                    }

                    // 打印正文
                    System.out
                            .println("--------------------------------------");
                    System.out.println("Response content: "
                            + EntityUtils.toString(entity, "UTF-8"));
                    System.out
                            .println("--------------------------------------");
                }
            } 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();
            }
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章