HttpClient基於表單登入


使用HttpClient庫,可以傳送請求或通過傳遞引數登入表單。

按照以下步驟登入表單。

第1步 - 建立一個HttpClient物件
HttpClients類的createDefault()方法返回類CloseableHttpClient的物件,該物件是HttpClient介面的基本實現。使用此方法建立一個HttpClient物件 -

CloseableHttpClient httpClient = HttpClients.createDefault();

第2步 - 建立RequestBuilder物件

RequestBuilder類用於通過向其新增引數來構建請求。如果請求型別是:PUTPOST,則它將引數作為URL編碼實體新增到請求中

使用post()方法建立RequestBuilder物件(型別為POST)。

//Building the post request object
RequestBuilder reqbuilder = RequestBuilder.post();

第3步 - 將Uri和引數設定為RequestBuilder。
使用RequestBuilder類的setUri()addParameter()方法將URI和引數設定為RequestBuilder物件。

//Set URI and parameters
RequestBuilder reqbuilder = reqbuilder.setUri("http://httpbin.org/post");
reqbuilder = reqbuilder1.addParameter("Name", "username").addParameter("password", "password");

第4步 - 構建HttpUriRequest物件
設定所需引數後,使用build()方法構建HttpUriRequest物件。

//Building the HttpUriRequest object
HttpUriRequest httppost = reqbuilder2.build();

第5步 - 執行請求
CloseableHttpClient物件的execute()方法接受HttpUriRequest(介面)物件(即:HttpGetHttpPostHttpPutHttpHead等)並返回響應物件。

通過將它傳遞給execute()方法來執行前面步驟中建立的HttpUriRequest

//Execute the request
HttpResponse httpresponse = httpclient.execute(httppost);

範例

以下範例演示了如何通過傳送登入憑據登入到表單。在這裡,我們向表單傳送了兩個引數 - usernamepassword,並嘗試列印訊息實體和請求的狀態。

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;

public class FormLoginExample {

   public static void main(String args[]) throws Exception {

      //Creating CloseableHttpClient object
      CloseableHttpClient httpclient = HttpClients.createDefault();

      //Creating the RequestBuilder object
      RequestBuilder reqbuilder = RequestBuilder.post();

      //Setting URI and parameters
      RequestBuilder reqbuilder1 = reqbuilder.setUri("http://httpbin.org/post");
      RequestBuilder reqbuilder2 = reqbuilder1.addParameter("Name", 
         "username").addParameter("password", "password");

      //Building the HttpUriRequest object
      HttpUriRequest httppost = reqbuilder2.build();

      //Executing the request
      HttpResponse httpresponse = httpclient.execute(httppost);

      //Printing the status and the contents of the response
      System.out.println(EntityUtils.toString(httpresponse.getEntity()));
      System.out.println(httpresponse.getStatusLine());
   }
}

執行上面範例程式碼,得到以下結果:

{
 "args": {},
 "data": "",
 "files": {},
 "form": {
 "Name": "username",
 "password": "password"
 },
 "headers": {
 "Accept-Encoding": "gzip,deflate",
 "Connection": "close",
 "Content-Length": "31",
 "Content-Type": "application/x-www-form-urlencoded; charset = UTF-8",
 "Host": "httpbin.org",
 "User-Agent": "Apache-HttpClient/4.5.6 (Java/1.8.0_91)"
 },
 "json": null,
 "origin": "217.216.145.180",
 "url": "http://httpbin.org/post"
}
HTTP/1.1 200 OK

如果表單儲存cookie,而不是建立預設的CloseableHttpClient物件。通過範例化BasicCookieStore類來建立CookieStore物件。

//Creating a BasicCookieStore object
BasicCookieStore cookieStore = new BasicCookieStore();

使用HttpClients類的custom()方法建立HttpClientBuilder

//Creating an HttpClientBuilder object
HttpClientBuilder clientbuilder = HttpClients.custom();

使用setDefaultCookieStore()方法將cookie儲存設定為用戶端構建器。

//Setting default cookie store to the client builder object
Clientbuilder = clientbuilder.setDefaultCookieStore(cookieStore);

使用build()方法構建CloseableHttpClient物件。

//Building the CloseableHttpClient object
CloseableHttpClient httpclient = clientbuilder1.build();

通過傳遞執行請求來構建上面指定的HttpUriRequest物件。如果頁面儲存cookie,則傳遞的引數將新增到cookie儲存中。

可以列印CookieStore物件的內容,在其中檢視引數(以及以前儲存的頁面)。

要列印cookie,請使用getCookies()方法從CookieStore物件獲取所有cookie。此方法返回List物件。使用Iterator列印列表物件內容,如下所示 -

//Printing the cookies
List list = cookieStore.getCookies();

System.out.println("list of cookies");
Iterator it = list.iterator();
if(it.hasNext()){
   System.out.println(it.next());
}