Apache HttpClient - 基于表单的登录

使用 HttpClient 库,您可以发送请求或通过传递参数登录到表单。

按照以下步骤登录表单。


步骤 1 - 创建一个 HttpClient 对象

HttpClients类的createDefault()方法返回一个CloseableHttpClient类的对象,它是HttpClient接口的基础实现 . 使用此方法,创建一个 HttpClient 对象 −

CloseableHttpClient httpClient = HttpClients.createDefault();

步骤 2 - 创建一个 RequestBuilder 对象

RequestBuilder 类用于通过向其添加参数来构建请求。 如果请求类型是 PUT 或 POST,它将参数作为 URL 编码实体添加到请求中

使用 post() 方法创建一个 RequestBuilder 对象(POST 类型)。

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

步骤 3 - 将 Uri 和参数设置为 RequestBuilder。

使用 RequestBuilder 类的 setUri()addParameter() 方法为 RequestBuilder 对象设置 URI 和参数。

//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(接口)对象(即 HttpGet、HttpPost、HttpPut、HttpHead 等)并返回一个响应对象。

通过将在前面步骤中创建的 HttpUriRequest 传递给 execute() 方法来执行它。

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

示例

以下示例演示如何通过发送登录凭据登录到表单。 在这里,我们发送了两个参数 − 用户名和密码 到表单并尝试打印消息实体和请求状态。

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": "117.216.245.180",
   "url": "http://httpbin.org/post"
}
HTTP/1.1 200 OK

使用 Cookie 登录表单

如果您的表单存储 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 对象。

如果页面存储了cookies,你传递的参数将被添加到cookie存储中。

您可以打印 CookieStore 对象的内容,您可以在其中查看您的参数(以及以前存储的页面以防万一)。

要打印 cookie,请使用 getCookies() 方法从 CookieStore 对象中获取所有 cookie。 此方法返回一个 List 对象。 使用迭代器,打印列表对象的内容,如下所示 −

//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());
}