建议使用响应处理程序处理HTTP响应。在本章中,我们将讨论如何创建响应处理程序以及如何使用它们来处理响应。
如果使用响应处理程序,则将自动释放所有HTTP连接。
创建响应处理程序
HttpClient API在org.apache.http.client
包中提供了一个名为ResponseHandler
的接口。为了创建响应处理程序,请实现此接口并覆盖其handleResponse()
方法。
每个响应都有一个状态代码,如果状态代码在200到300之间,则表示该操作已成功接收,理解和接受。因此,在我们的示例中,使用此类状态代码处理响应的实体。
使用响应处理程序执行请求
按照下面给出的步骤使用响应处理程序执行请求。
第1步 - 创建HttpClient对象
HttpClients
类的createDefault()
方法返回类CloseableHttpClient
的对象,该对象是HttpClient
接口的基本实现。使用此方法创建一个HttpClient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
第2步 - 实例化响应处理程序
使用以下代码行实例化上面创建的响应处理程序对象 -
ResponseHandler<String> responseHandler = new MyResponseHandler();
第3步 - 创建一个HttpGet对象
HttpGet
类表示HTTP GET请求,该请求使用URI检索给定服务器的信息。
通过实例化HttpGet类并将表示URI作为参数的字符串传递给其构造函数来创建HttpGet请求。
ResponseHandler<String> responseHandler = 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<String>{
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<String> responseHandler = new MyResponseHandler();
//Create an HttpGet object
HttpGet httpget = new HttpGet("http://www.kaops.com/");
//Execute the Get request by passing the response handler object and HttpGet object
String httpresponse = httpclient.execute(httpget, responseHandler);
System.out.println(httpresponse);
}
}
执行上面示例代码,得到以下结果:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>考评师 - 一个专注于面试题和知识测评的网站</title>
<meta name="baidu-site-verification" content="SMo5w14fvk" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="keywords" content="考试,面试,面试题,考试题">
<meta name="description" content="考评师网是一个专注于提供知识考评测试和面试题的网站。汇集了各个行业,各种技术,知识等面试题和知识测试。">
<link rel="stylesheet" href="/static/layui/css/layui.css">
<link rel="stylesheet" href="/static/css/global.css">
</head>
<body>
.....