建议使用响应处理程序处理HTTP响应.在本章中,我们将讨论如何创建响应处理程序以及如何使用它们来处理响应.
如果使用响应处理程序,将自动释放所有HTTP连接.
创建响应处理程序
HttpClient API在包<中提供了一个名为 ResponseHandler 的接口b> org.apache.http.client.为了创建响应处理程序,实现此接口
并覆盖其 handleResponse()方法.
每个响应都有一个状态代码,如果状态代码在200到300之间,则表示该操作已成功接收,理解和接受.因此,在我们的示例中,我们将使用此类状态代码处理响应的实体.
使用响应处理程序执行请求
按照步骤操作下面给出使用响应处理程序执行请求.
步骤1 - 创建HttpClient对象
createDefault() HttpClients 类的方法返回类 CloseableHttpClient 的对象,它是 HttpClient 接口的基本实现.使用此方法创建一个HttpClient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
步骤2 - 实例化响应处理程序
使用以下代码行实现上面创建的响应处理程序对象&minus ;
ResponseHandlerresponseHandler = new MyResponseHandler();
步骤3 - 创建HttpGet对象
HttpGet 类表示HTTP GET请求使用URI检索给定服务器的信息.
通过实例化HttpGet类并将表示URI作为参数的字符串传递给其构造函数来创建HttpGet请求.
ResponseHandlerresponseHandler = new MyResponseHandler();
步骤4 - 使用响应处理程序执行Get请求
CloseableHttpClient 类具有 execute()方法的变体,它接受两个对象 ResponseHandler 和HttpUriRequest,并返回一个响应对象.
String httpResponse = httpclient.execute(httpget, responseHandler);
示例
以下示例演示了响应处理程序的用法.
import java.io.IOException;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.ResponseHandler;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;class MyResponseHandler implements ResponseHandler{ public String handleResponse(final HttpResponse response) throws IOException{ //Get the status of the response int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); if(entity == null) { return ""; } else { return EntityUtils.toString(entity); } } else { return ""+status; } }}public class ResponseHandlerExample { public static void main(String args[]) throws Exception{ //Create an HttpClient object CloseableHttpClient httpclient = HttpClients.createDefault(); //instantiate the response handler ResponseHandler responseHandler = new MyResponseHandler(); //Create an HttpGet object HttpGet httpget = new HttpGet("http://www.IT屋.com/"); //Execute the Get request by passing the response handler object and HttpGet object String httpresponse = httpclient.execute(httpget, responseHandler); System.out.println(httpresponse); } }
输出
以上程序生成以下输出 :
. . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . .