1. 程式人生 > >Apache HttpClient4.2.5 模擬post、登入並訪問驗證授權資料

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

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,下次訪問將自動附帶上。