Apache HttpClient4.2.5 類比post、登入並訪問驗證授權資料

來源:互聯網
上載者:User

1.HttpClient 簡介

                  (百度文庫)HttpClient 是 Apache Jakarta Common 下的子項目,可以用來提供高效的、最新的、功能豐富的支援 HTTP 協議的用戶端編程工具包,並且它支援 HTTP 協議最新的版本和建議。本文首先介紹
HTTPClient,然後根據作者實際工作經驗給出了一些常見問題的解決方案。

HttpClient:

                      http://hc.apache.org/downloads.cgi

                      我們選擇:HttpClient 4.2.5 (GA)(4.2.5.zip)(下載binary就可以了,不用source)

2.使用方式:

                      下載完成後解壓zip包,在\httpcomponents-client-4.2.5-bin\httpcomponents-client-4.2.5\lib下可以看到所有的包都在裡面了,我們接下來的例子中使用其中3個包,分別是:

         httpcore-4.2.4.jar

         httpclient-4.2.5.jar

         commons-logging-1.1.1.jar

 

         將這3個jar包添加到項目中,然後簡單封裝HttpClient類如下:

package com.test;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.ParseException;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.conn.scheme.Scheme;import org.apache.http.conn.ssl.SSLSocketFactory;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.security.*;import java.security.cert.CertificateException;import java.util.*;public class HT {    HttpClient httpclient=new DefaultHttpClient();    /**     * 發送 post請求訪問本地應用並根據傳遞參數不同返回不同結果     */    public String post(String url,String respEncoding) {        return post(url,"UTF-8",respEncoding,new ArrayList<NameValuePair>());    }    /**     * 發送 post請求訪問本地應用並根據傳遞參數不同返回不同結果     */    public String post(String url,String reqEncoding,String respEncoding,List<NameValuePair> param) {        String resStr = "";        // 建立httppost        HttpPost httppost = new HttpPost(                url);        // 建立參數隊列        List<NameValuePair> formparams = param;        UrlEncodedFormEntity uefEntity;        try {            uefEntity = new UrlEncodedFormEntity(formparams, reqEncoding);            httppost.setEntity(uefEntity);            HttpResponse response;            response = httpclient.execute(httppost);            HttpEntity entity = response.getEntity();            if (entity != null) {                resStr = EntityUtils.toString(entity,respEncoding);            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (UnsupportedEncodingException e1) {            e1.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            // 關閉串連,釋放資源           // httpclient.getConnectionManager().shutdown();        }        return resStr;    }    /**     * 發送 get請求     */    public String get(String url) {        //httpclient = new DefaultHttpClient();        String resStr = "";        try {            // 建立httpget.            HttpGet httpget = new HttpGet(url);            // 執行get請求.            HttpResponse response = httpclient.execute(httpget);            // 擷取響應實體            HttpEntity entity = response.getEntity();            // 列印響應狀態            System.out.println(response.getStatusLine());            if (entity != null) {                // 列印響應內容長度//                System.out.println("Response content length: "//                        + entity.getContentLength());                // 列印響應內容//                System.out.println("Response content: "//                        + EntityUtils.toString(entity));                resStr=EntityUtils.toString(entity);            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (ParseException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            // 關閉串連,釋放資源            //httpclient.getConnectionManager().shutdown();        }        return resStr;    }

調用:

import org.apache.http.NameValuePair;import org.apache.http.message.BasicNameValuePair;import java.util.ArrayList;import java.util.List;/** * Created with IntelliJ IDEA. * User: Administrator * Date: 13-7-25 * Time: 下午4:05 * To change this template use File | Settings | File Templates. */public class MainClass {    public static void main(String[] args) {        HT ht = new HT();//構造參數        List<NameValuePair> list =new ArrayList<NameValuePair>();        list.add(new BasicNameValuePair("li", "house"));//登入參數        System.out.println(ht.post("http://localhost:2375/Default.aspx", "UTF-8", "UTF-8", list));//先post登入也賣弄        System.out.println(ht.get("http://localhost:2375/WebForm1.aspx"));//此頁面是需要登入才能訪問的頁面    }}

注意點:NameValuePair和BasicNameValuePair都是httpclient包裡的,自動產生時可能給你添加jdk中的,需要手動改一下。

 

3.最後

1.HttpClient支援SSL串連,代碼請另百度

2.//httpclient.getConnectionManager().shutdown();被屏蔽掉和HttpClient httpclient=new DefaultHttpClient();定義為全域變數的原因就是這樣才能保證第一次post登入之後,第二次訪問頁面不會提示未登入,通俗的講只要HttpClient的執行個體沒有重新賦值,它會自動儲存cookie,下次訪問將自動附帶上。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.