Apache Httpclient 简明教程

Apache HttpClient - Form-Based Login

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

按照下面给出的步骤,来登录表单。

Step 1 - Create an HttpClient object

@ {s15}`类的@ {s14}`方法返回`@ {s16}`类的对象,该对象是 HttpClient 接口的基本实现。使用此方法,创建一个 HttpClient 对象 -

CloseableHttpClient httpClient = HttpClients.createDefault();

Step 2 - Create a RequestBuilder object

类`@ {s17}`用于通过向其中添加参数来构建请求。如果请求类型为PUT或POST,它会将这些参数作为URL编码实体添加到请求中

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

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

Step 3 - Set Uri and parameters to the RequestBuilder.

使用RequestBuilder 类的`@ {s18}`和`@ {s19}`方法将URI和参数设置到 RequestBuilder 对象。

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

Step 4 - Build the HttpUriRequest object

在设置了所需的参数之后,使用`@ {s21}`方法构建`@ {s20}`对象。

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

Step 5 - Execute the request

CloseableHttpClient 对象的`execute`方法接受`HttpUriRequest`(接口)对象(例如 HttpGet、HttpPost、HttpPut、HttpHead 等)并返回一个响应对象。

通过将创建好的`HttpUriRequest`传递给`@ {s22}`方法,执行在前一步创建的`HttpUriRequest`。

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

Example

以下示例展示了如何通过发送登录凭据来登录表单。在此,我们已将两个参数`@ {s23}`发送到表单,并试着打印消息实体和请求状态。

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

Output

执行后,上述程序会生成以下输出−

{
   "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

Form Login with Cookies

如果你的表单存储了 cookie,则不创建默认`@ {s24}`对象。

Create a CookieStore object 通过实例化 BasicCookieStore 类。

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

Create a HttpClientBuilder 使用 HttpClientscustom() 方法。

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

Set the cookie store to the client builder 使用 setDefaultCookieStore() 方法。

//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 对象。使用迭代器,按照如下方式打印列表对象的內容:

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