1. 程式人生 > >HttpClient 操作工具類---

HttpClient 操作工具類---

原文地址:

設定post方法的header,增加紅色字型部分的配置:
HttpClient client = new HttpClient();
client.getParams().setBooleanParameter(
"http.protocol.expect-continue", false);
PostMethod method = new PostMethod(url);

method.addRequestHeader("Connection", "close");

一。 http 工作 大至 原理

HTTP工作原理 
1.客戶端和伺服器。
2.建立連線,客戶端向伺服器傳送一個請求。
3.伺服器接受到請求後,向客戶端發出響應資訊。
4.客戶端與伺服器斷開連結。

請求報文與響應報文。
請求報文格式:
請求行-->通用資訊頭-->請求頭-->實體頭-->報文主體
響應報文格式:
狀態行-->通用資訊頭-->相應頭-->實體頭-->報文主體

android 集成了org.apache.http.client.HttpClient; 可以直接實現簡單的htttp Get 和 Post 操作 但是不支援 多部post 操作 。 要實現 多部分post 操作還需要導 額外 jar包 這裡就不介紹了。

實現一個 http 操作

1 。需要生成一個Http Client 客戶端物件 。

2。 生成響應的請求物件 。

3。接受發回的資訊 。

4.。解析返回的資訊。

直接看 get 請求操作 。

public String httpGet(String url, String params) throws Exception{  

        String result=""; //返回資訊
        if (null!=params&&!params.equals(""))
        {
            url += "?" + params;
        }
        //建立一個httpGet請求
HttpGet request=new HttpGet(url); //建立一個htt客戶端 HttpClient httpClient=new DefaultHttpClient(); //接受客戶端發回的響應 HttpResponse httpResponse=httpClient.execute(request); int statusCode=httpResponse.getStatusLine().getStatusCode(); if(statusCode==HttpStatus.SC_OK){ //得到客戶段響應的實體內容 HttpEntity responseHttpEntity=httpResponse.getEntity(); //得到輸入流 InputStream in=responseHttpEntity.getContent(); //得到輸入流的內容 result=getData(in); } Log.d(TAG, statusCode+""); return result; }

post 操作




幾個額外的輔助方法

/**
     * 讀取返回的資訊
     * @param in
     * @return
     */
    private String getData(InputStream in) {
        String result="";
        StringBuilder sb=new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String line = "";
        try {
            while ((line = br.readLine()) != null) {
                //result = result + line;
                sb.append(line);
            }
            br.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (result != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }  


/**
     * 輸入流轉換成字串
     * @param is: 輸入流
     * @return 字串物件
     */
    private static String InputStreamToString(InputStream is){
        BufferedReader reader = null;
        StringBuffer responseText = null;
        String readerText = null;
        try {
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            responseText = new StringBuffer();
            readerText = reader.readLine();
            while(readerText != null){
                responseText.append(readerText);
                responseText.append(System.getProperty("line.separator"));
                readerText = reader.readLine();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseText.toString();
    }
/**
     * 將cookie寫入指定檔案
     * @param cookies: cookie
     * @param fileName: 檔名
     */
    private static void write(Cookie[] cookies, String fileName){
        try {
            String path = System.getProperty("user.home") + "\\" + fileName;
            File file = new File(path);
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            for(Cookie c : cookies){
                bw.append(c.toString());
                bw.append(System.getProperty("line.separator"));
            }
            bw.flush();
            bw.close();
            Runtime.getRuntime().exec("explorer " + path + "");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    
如何 post json格式的資料,並附加http頭,接受返回資料,請看下面的程式碼:

[java] view plaincopy
private void HttpPostData() {
try {
    HttpClient httpclient = new DefaultHttpClient();
    String uri = "http://www.yourweb.com";
    HttpPost httppost = new HttpPost(uri);
    //新增http頭資訊
    httppost.addHeader("Authorization", "your token"); //認證token
    httppost.addHeader("Content-Type", "application/json");
    httppost.addHeader("User-Agent", "imgfornote");
    //http post的json資料格式:  {"name": "your name","parentId": "id_of_parent"}
    JSONObject obj = new JSONObject();
    obj.put("name", "your name");
    obj.put("parentId", "your parentid");
    httppost.setEntity(new StringEntity(obj.toString()));
    HttpResponse response;
    response = httpclient.execute(httppost);
    //檢驗狀態碼,如果成功接收資料
    int code = response.getStatusLine().getStatusCode();
    if (code == 200) {
        String rev = EntityUtils.toString(response.getEntity());//返回json格式: {"id": "27JpL~j4vsL0LX00E00005","version": "abc"}
        obj = new JSONObject(rev);
        String id = obj.getString("id");
        String version = obj.getString("version");
    }
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    } catch (Exception e) {
    }
}
主要用到的類有:org.apache.http.client.HttpClient 、org.apache.http.client.methods.HttpPost 和 org.json.JSONObject




請求行 ,是一個方法符號開頭 ,後面跟著請求 URI和協議的版本, 以CRLF作為結尾 . 請求後以空格分隔. 除了作為結尾的 CRLF(回車換行)外,不允許出現單獨的CR和LF字元,格式如下:
Method Request-URI HTTP-Version CRLF
例如 : GET /test.html HTTP/1.1 (CRLF)
HTTP請求方法 : GET POST HEAD DELETE PUT
POST方法用於向伺服器傳送請求,要求伺服器接受附在請求後面的資料.POST方法在表單提交的時候用的最多 .
例如: 
POST /login.jsp HTTP/1.1 (CRLF)
Accept:image/gif (CRLF) (...)
........
Host:www.sample.com (CRLF)
(CRLF)
[email protected]=123456 兩個(CRLF)之後加上引數
HEAD方法只是請求訊息報頭,而不是完整的內容. 通常用於測試超連結的有效性.

HTTP響應 
HTTP-Version Status-Code Reason-Phrase CRLF
例如 : HTTP/1.1 200 OK (CRLF)

狀態分類 
1xx 提示資訊
2xx 請求成功
3xx 重定向
4xx 客戶端錯誤
5xx 伺服器錯誤
HTTP訊息有客戶端到伺服器的請求和伺服器到客戶端的響應組成.
訊息都是由開始行,訊息報頭(可選),空行(只有CRLF的行),訊息正文(可選)組成.
對於請求訊息,開始行就是請求行,對於響應訊息,開始行就是狀態行.

Apache HttpClient 是很方便的 Java 開源的訪問 HTTP 資源的元件。網站上的資源不總是能匿名訪問的,很多都需要登陸後才能操作,且不說論壇裡登陸後才能發言,就是某些稍顯敏感的 XML 等資訊也是登陸後才能獲取到的。

沒問題,HttpClient 能讓你做到,它提供了 Basic 和 Form-Based 兩種驗證方式。登陸後獲得伺服器端發來的 Cookie 作為下一次訪問的憑證, 讓服務端認為你還是個合法使用者。服務端不是用 Session 來維護會話的嗎?是的,Session 也要有個載體,Cookie 了。或有時 Java Web 會用 jsessionid 引數在服務端與客戶端來回關聯 Session 資訊,也沒問題,HttpClient 同樣能勝任。

下面主要說明 Form-Based 的驗證方式,Basic 的驗證簡單列了幾行程式碼,還未實踐,具體可參考文後的連結。

看 Form-Based 方式的演示程式碼,如果登陸時需要一個驗證碼的話,那只有自己想辦法怎麼得到這個碼了,登陸時誰都想無碼:

package cc.unmi.httpclient; 

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.junit.Test;

public class HttpClientLogin {

    public static void main(String[] args){
        //登陸 Url
        String loginUrl = "http://localhost/unmi/login.html";

        //需登陸後訪問的 Url
        String dataUrl = "http://localhost/unmi/user_info.html?userid=123456";

        HttpClient httpClient = new HttpClient();

        //模擬登陸,按實際伺服器端要求選用 Post 或 Get 請求方式
        PostMethod postMethod = new PostMethod(loginUrl);

        //設定登陸時要求的資訊,一般就使用者名稱和密碼,驗證碼自己處理了
        NameValuePair[] data = {
                new NameValuePair("username", "Unmi"),
                new NameValuePair("password", "123456"),
                new NameValuePair("code", "anyany")
        };
        postMethod.setRequestBody(data);

        try {
            //設定 HttpClient 接收 Cookie,用與瀏覽器一樣的策略
            httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            httpClient.executeMethod(postMethod);

            //獲得登陸後的 Cookie
            Cookie[] cookies=httpClient.getState().getCookies();
            String tmpcookies= "";
            for(Cookie c:cookies){
                tmpcookies += c.toString()+";";
            }

            //進行登陸後的操作
            GetMethod getMethod = new GetMethod(dataUrl);

            //每次訪問需授權的網址時需帶上前面的 cookie 作為通行證
            getMethod.setRequestHeader("cookie",tmpcookies);

            //你還可以通過 PostMethod/GetMethod 設定更多的請求後資料
            //例如,referer 從哪裡來的,UA 像搜尋引擎都會表名自己是誰,無良搜尋引擎除外
            postMethod.setRequestHeader("Referer", "http://unmi.cc");
            postMethod.setRequestHeader("User-Agent","Unmi Spot");

            httpClient.executeMethod(getMethod);

            //打印出返回資料,檢驗一下是否成功
            String text = getMethod.getResponseBodyAsString();
            System.out.println(text);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Basic 驗證的簡單程式碼導引,還未親試:

HttpClient client = new HttpClient();

// 1
client.getState().setCredentials(
    new AuthScope("unmi.cc", 80, AuthScope.ANY_REALM),
    new UsernamePasswordCredentials("username", "password")
);

// 2
client.getParams().setAuthenticationPreemptive(true);

// 3
GetMethod getMothod = new GetMethod("http://unmi.cc/twitter");

// 4
getMothod.setDoAuthentication( true );

// 5
int status = client.executeMethod( getMothod );

http://unmi.cc/httpclient-login-session

999999999999999999999999

post步驟 解析json資料(向伺服器傳遞,接受伺服器傳遞))
www.MyException.Cn   釋出於:2012-08-11 20:50:31   瀏覽:13次

httpClient post方法 解析json資料(向伺服器傳遞,接受伺服器傳遞))

public class json extends Activity {
    public Context context;
    private TextView textView1;
    public static String URL = "http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
    private DefaultHttpClient httpClient;
    StringBuilder result = new StringBuilder();
    private static final int TIMEOUT = 60;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        HttpParams paramsw = createHttpParams();
        httpClient = new DefaultHttpClient(paramsw);
        HttpPost post = new HttpPost(               "http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl");
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("name", "this is post"));
        try {
            //向伺服器寫json
            JSONObject json = new JSONObject();
            Object email = null;
            json.put("email", email);
            Object pwd = null;
           json.put("password", pwd);
            StringEntity se = new StringEntity( "JSON: " + json.toString());
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.setEntity(se);
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse httpResponse = httpClient.execute(post);

            int httpCode = httpResponse.getStatusLine().getStatusCode();
            if (httpCode == HttpURLConnection.HTTP_OK&&httpResponse!=null) {
                Header[] headers = httpResponse.getAllHeaders();
                HttpEntity entity = httpResponse.getEntity();
                Header header = httpResponse.getFirstHeader("content-type");
                //讀取伺服器返回的json資料(接受json伺服器資料)
                InputStream inputStream = entity.getContent();
               InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader reader = new BufferedReader(inputStreamReader);// 讀字串用的。
                String s;
                while (((s = reader.readLine()) != null)) {
                    result.append(s);

                }
                reader.close();// 關閉輸入流
                //在這裡把result這個字串個給JSONObject。解讀裡面的內容。
                JSONObject jsonObject = new JSONObject(result.toString());
                String re_username = jsonObject.getString("username");
                String re_password = jsonObject.getString("password");
                int re_user_id = jsonObject.getInt("user_id");
               setTitle("使用者id_"+re_user_id);
                Log.v("url response", "true="+re_username);
                Log.v("url response", "true="+re_password);

            } else {

                textView1.setText("Error Response" + httpResponse.getStatusLine().toString());

            }
        } catch (UnsupportedEncodingException e) {
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null) {
                httpClient.getConnectionManager().shutdown();// 最後關掉連結。
                httpClient = null;
            }
        }
    }

    public static final HttpParams createHttpParams() {
        final HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setStaleCheckingEnabled(params, false);
        HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000);
        HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000);
        HttpConnectionParams.setSocketBufferSize(params, 8192 * 5);
        return params;
    }
}

348888888888888888

HttpClient程式包是一個實現了 HTTP 協議的客戶端程式設計工具包,要想熟練的掌握它,必須熟悉 HTTP協議。一個最簡單的呼叫如下:

import java.io.IOException;

import org.apache.http.HttpResponse;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpUriRequest;

import org.apache.http.impl.client.DefaultHttpClient;

public class Test {

public static void main(String[] args) {

// 核心應用類

HttpClient httpClient = new DefaultHttpClient();

// HTTP請求

HttpUriRequest request =

new HttpGet("http://localhost/index.html");

// 列印請求資訊

System.out.println(request.getRequestLine());

try {

// 傳送請求,返回響應

HttpResponse response = httpClient.execute(request);

// 列印響應資訊

System.out.println(response.getStatusLine());

} catch (ClientProtocolException e) {

// 協議錯誤

e.printStackTrace();

} catch (IOException e) {

// 網路異常

e.printStackTrace();

}

}

}

如果HTTP伺服器正常並且存在相應的服務,則上例會打印出兩行結果:

GET http://localhost/index.html HTTP/1.1

HTTP/1.1 200 OK

核心物件httpClient的呼叫非常直觀,其execute方法傳入一個request物件,返回一個response物件。使用 httpClient發出HTTP請求時,系統可能丟擲兩種異常,分別是ClientProtocolException和IOException。第一種異常的發生通常是協議錯誤導致,如在構造HttpGet物件時傳入的協議不對(例如不小心將”http”寫成”htp”),或者伺服器端返回的內容不符合HTTP協議要求等;第二種異常一般是由於網路原因引起的異常,如HTTP伺服器未啟動等。

從實際應用的角度看,HTTP協議由兩大部分組成:HTTP請求和HTTP響應。那麼HttpClient程式包是如何實現HTTP客戶端應用的呢?實現過程中需要注意哪些問題呢?

HTTP請求

HTTP 1.1由以下幾種請求組成:GET, HEAD, POST, PUT, DELETE, TRACE and OPTIONS, 程式包中分別用HttpGet, HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, and HttpOptions 這幾個類建立請求。所有的這些類均實現了HttpUriRequest介面,故可以作為execute的執行引數使用。

所有請求中最常用的是GET與POST兩種請求,與建立GET請求的方法相同,可以用如下方法建立一個POST請求:

HttpUriRequest request = new HttpPost(

"http://localhost/index.html");

HTTP請求格式告訴我們,有兩個位置或者說兩種方式可以為request提供引數:request-line方式與request-body方式。

request-line

request-line方式是指在請求行上通過URI直接提供引數。

(1)

我們可以在生成request物件時提供帶引數的URI,如:

HttpUriRequest request = new HttpGet(

"http://localhost/index.html?param1=value1&param2=value2");

(2)

另外,HttpClient程式包為我們提供了URIUtils工具類,可以通過它生成帶引數的URI,如:

URI uri = URIUtils.createURI("http", "localhost", -1, "/index.html",

"param1=value1&param2=value2", null);

HttpUriRequest request = new HttpGet(uri);

System.out.println(request.getURI());

上例的列印結果如下:

http://localhost/index.html?param1=value1&param2=value2

(3)

需要注意的是,如果引數中含有中文,需將引數進行URLEncoding處理,如:

String param = "param1=" + URLEncoder.encode("中國", "UTF-8") + "&param2=value2";

URI uri = URIUtils.createURI("http", "localhost", 8080,

"/sshsky/index.html", param, null);

System.out.println(uri);

上例的列印結果如下:

http://localhost/index.html?param1=%E4%B8%AD%E5%9B%BD&param2=value2

(4)

對於引數的URLEncoding處理,HttpClient程式包為我們準備了另一個工具類:URLEncodedUtils。通過它,我們可以直觀的(但是比較複雜)生成URI,如:

List params = new ArrayList();

params.add(new BasicNameValuePair("param1", "中國"));

params.add(new BasicNameValuePair("param2", "value2"));

String param = URLEncodedUtils.format(params, "UTF-8");

URI uri = URIUtils.createURI("http", "localhost", 8080,

"/sshsky/index.html", param, null);

System.out.println(uri);

上例的列印結果如下:

http://localhost/index.html?param1=%E4%B8%AD%E5%9B%BD&param2=value2

request-body

與request-line方式不同,request-body方式是在request-body中提供引數,此方式只能用於POST請求。在 HttpClient程式包中有兩個類可以完成此項工作,它們分別是UrlEncodedFormEntity類與MultipartEntity類。這兩個類均實現了HttpEntity介面。

(1)

使用最多的是UrlEncodedFormEntity類。通過該類建立的物件可以模擬傳統的HTML表單傳送POST請求中的引數。如下面的表單:

<form action="http://localhost/index.html" method="POST">

<input type="text" name="param1" value="中國"/>

<input type="text" name="param2" value="value2"/>

<inupt type="submit" value="submit"/>

</form>

我們可以用下面的程式碼實現:

List formParams = new ArrayList();

formParams.add(new BasicNameValuePair("param1", "中國"));

formParams.add(new BasicNameValuePair("param2", "value2"));

HttpEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");

HttpPost request = new HttpPost(“http://localhost/index.html”);

request.setEntity(entity);

當然,如果想檢視HTTP資料格式,可以通過HttpEntity物件的各種方法取得。如:

List formParams = new ArrayList();

formParams.add(new BasicNameValuePair("param1", "中國"));

formParams.add(new BasicNameValuePair("param2", "value2"));

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");

System.out.println(entity.getContentType());

System.out.println(entity.getContentLength());

System.out.println(EntityUtils.getContentCharSet(entity));

System.out.println(EntityUtils.toString(entity));

上例的列印結果如下:

Content-Type: application/x-www-form-urlencoded; charset=UTF-8

39

UTF-8

param1=%E4%B8%AD%E5%9B%BD&param2=value2

(2)

除了傳統的application/x-www-form-urlencoded表單,我們另一個經常用到的是上傳檔案用的表單,這種表單的型別為 multipart/form-data。在HttpClient程式擴充套件包(HttpMime)中專門有一個類與之對應,那就是 MultipartEntity類。此類同樣實現了HttpEntity介面。如下面的表單:

<form action="http://localhost/index.html" method="POST"

enctype="multipart/form-data">

<input type="text" name="param1" value="中國"/>

<input type="text" name="param2" value="value2"/>

<input type="file" name="param3"/>

<inupt type="submit" value="submit"/>

</form>

我們可以用下面的程式碼實現:

MultipartEntity entity = new MultipartEntity();

entity.addPart("param1", new StringBody("中國", Charset.forName("UTF-8")));

entity.addPart("param2", new StringBody("value2", Charset.forName("UTF-8")));

entity.addPart("param3", new FileBody(new File("C:\\1.txt")));

HttpPost request = new HttpPost(“http://localhost/index.html”);

request.setEntity(entity);

HTTP響應

HttpClient程式包對於HTTP響應的處理較之HTTP請求來說是簡單多了,其過程同樣使用了HttpEntity介面。我們可以從 HttpEntity物件中取出資料流(InputStream),該資料流就是伺服器返回的響應資料。需要注意的是,HttpClient程式包不負責解析資料流中的內容。如:

HttpUriRequest request = ...;

HttpResponse response = httpClient.execute(request);

// 從response中取出HttpEntity物件

HttpEntity entity = response.getEntity();

// 檢視entity的各種指標

System.out.println(entity.getContentType());

System.out.println(entity.getContentLength());

System.out.println(EntityUtils.getContentCharSet(entity));

// 取出伺服器返回的資料流

InputStream stream = entity.getContent();

// 以任意方式操作資料流stream

// 呼叫方式 略

附註:

本文說明的是HttpClient 4.0.1,該程式包(包括依賴的程式包)由以下幾個JAR包組成:

commons-logging-1.1.1.jar

commons-codec-1.4.jar

httpcore-4.0.1.jar

httpclient-4.0.1.jar

apache-mime4j-0.6.jar

httpmime-4.0.1.jar
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

現在Apache已經發布了:HttpCore 4.0-beta3、HttpClient 4.0-beta1。

到此處可以去下載這些原始碼:http://hc.apache.org/downloads.cgi

另外,還需要apache-mime4j-0.5.jar 包。

在這裡先寫個簡單的POST方法。

package test;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class Test2 {
    public static void main(String[] args) throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();      //例項化一個HttpClient
        HttpResponse response = null;
        HttpEntity entity = null;
        httpclient.getParams().setParameter(
                ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);  //設定cookie的相容性
        HttpPost httpost = new HttpPost("http://127.0.0.1:8080/pub/jsp/getInfo");           //引號中的引數是:servlet的地址
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("jqm", "fb1f7cbdaf2bf0a9cb5d43736492640e0c4c0cd0232da9de"));
        //   BasicNameValuePair("name", "value"), name是post方法裡的屬性, value是傳入的引數值
        nvps.add(new BasicNameValuePair("sqm", "1bb5b5b45915c8"));
        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));            //將引數傳入post方法中
        response = httpclient.execute(httpost);                                               //執行
        entity = response.getEntity();                                                             //返回伺服器響應
        try{
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());                           //伺服器返回狀態
            Header[] headers = response.getAllHeaders();                    //返回的HTTP頭資訊
            for (int i=0; i<headers.length; i++) {
            System.out.println(headers[i]);
            }
            System.out.println("----------------------------------------");
            String responseString = null;
            if (response.getEntity() != null) {
            responseString = EntityUtils.toString(response.getEntity());      / /返回伺服器響應的HTML程式碼
            System.out.println(responseString);                                   //打印出伺服器響應的HTML程式碼
            }
        } finally {
            if (entity != null)
            entity.consumeContent();                                                   // release connection gracefully
        }
        System.out.println("Login form get: " + response.getStatusLine());
        if (entity != null) {
        entity.consumeContent();
        }
    }
}

HttpClient4.0 學習例項 - 頁面獲取

HttpClient 4.0出來不久,所以網路上面相關的例項教程不多,搜httpclient得到的大部分都是基於原 Commons HttpClient 3.1 (legacy) 包的,官網下載頁面:http://hc.apache.org/downloads.cgi,如果大家看了官網說明就明白httpclient4.0是從原包分支出來獨立成包的,以後原來那個包中的httpclient不會再升級,所以以後我們是用httpclient新分支,由於4.0與之前的3.1包結構以及介面等都有較大變化,所以網上搜到的例項大部分都是不適合4.0的,當然,我們可以通過那些例項去琢磨4.0的用法,我也是新手,記錄下學習過程方便以後檢索

相關推薦

HttpClient 操作工具---

原文地址: 設定post方法的header,增加紅色字型部分的配置: HttpClient client = new HttpClient(); client.getParams().setBooleanParameter( "http.protocol.expect-contin

PreferencesUtils【SharedPreferences操作工具

ast 效果圖 void 垃圾清理 extends editor nac xtend git 版權聲明:本文為博主原創文章,未經博主允許不得轉載。 前言 可以替代ACache用來保存用戶名、密碼。 相較於Acache,不存在使用獵豹清理大師進行垃圾清理的時候把緩存的數

C#的access操作工具

C# access 操作工具類 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.OleDb; using System.Data

日期操作工具

ret catch pre pri 必須 led mem systemd stack 相關代碼如下 public class DateUtil { /** * * @param dateStyle 日期的樣式:如yyyyMMddHH

文件操作工具FileUtils

println 條件 == buffered ade mef cto override replace package yqw.java.util;import java.io.BufferedInputStream;import java.io.BufferedOutpu

常用判空操作工具

tis esc mail pre ati bst gradle otn ali 一、項目上校驗空和空集合地方非常多,可以編寫一個工具類統一校驗 package com.moy.custom.utils; import java.util.Collection; impo

c++對properties配置文件操作工具

c++ properties code源代碼GitHub路徑:源代碼地址下載 最近要使用c++對windows api相關接口的封裝,有2個接口要求讀寫properties文件。原以為網上應該有一大堆資料的,結果拜BAI度的大恩大德,一點相關的資料都沒有。那就只能自己動手豐衣足食。再次感謝十分強大只是找不到相

C#文件夾權限操作工具

輔助類 ace ont tex bject per right adding IT using System; using System.Collections.Generic; using System.IO; using System.Linq; using

JavaAes加密操作工具

ssi port castle 如果 ddp arrays array xfire instance package com.king.weixin.util;import java.io.UnsupportedEncodingException;import java.s

對JAVA資原始檔操作工具

package com.kkmall.risk.common.utils; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import jav

Redis | 嘗試封裝一個操作工具

介紹 本次主要介紹以下內容: 1、SpringMVC整合Redis 2、Spring Boot整合Redis(上) 3、Spring Boot整合Redis(中) 4、Spring Boot整合Redis(下) 5、使用redis為我們提供jar進行封裝 6、使用Spring Boot提供的

HttpClient請求工具

import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.htt

jedis 操作工具

包括連線池的使用及 jedis對string 、set、sortset、list、hash的所有常規操作。 package com.yufei.core.util.jedis; import java.util.List; import java.util.Map; import java.u

java 時間操作工具

時間操作工具類CalendarUtil 裡面包含方法有: 獲取當前時間getInstance 字串按照格式轉換成時間strToDate 時間格式化dateToStr 獲取當天零點getSame

整理的關於Java對mongodb進行的CURD操作工具及原始碼

package com.iceter.DataBase; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.bson.Document; import org.bson.conversi

php的mysql操作工具pdo和mysqli

從php7開始mysql擴充套件庫已經被全面移除,原因暫不清楚,官方推薦我們使用mysqli和pdo,這次就針對pdo和mysqli分享下我的兩個工具類 1 PDO的mysql操作工具類 這種方式已經用的越來越多了,pdo使用面向物件的方式操作資料庫,pdo是很多人都比較

Access資料庫操作,Mdb檔案操作工具,UCanAccess使用

  Access資料庫操作,Mdb檔案操作工具類,UCanAccess使用     ================================ ©Copyright 蕃薯耀 2018年12月27日 http://fanshuyao.iteye.com/

通過泛型和反射構建一個簡單的集合操作工具

      平時在操作集合物件的時候(比如List);我想一次新增大於一個數據的時候,往往需要通過一個集合物件呼叫兩次add方法,比如: List<Person> personList=new ArrayList<>(); Person p1=n

Java檔案操作工具FileUtils

package com.suobei.xinzhiying.base.utils.file; import com.suobei.xinzhiying.base.result.ResponseMap; import com.suobei.xinzhiying.base.utils.aliy

檔案操作工具: 檔案/目錄的建立、刪除、移動、複製、zip壓縮與解壓.

FileOperationUtils.java package com.xnl.utils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import jav