Apache HttpClient - 响应处理器
建议使用响应处理器处理HTTP响应。本章将讨论如何创建响应处理器以及如何使用它们来处理响应。
如果使用响应处理器,所有HTTP连接将自动释放。
创建响应处理器
HttpClient API 提供了一个名为ResponseHandler的接口,位于org.apache.http.client包中。要创建响应处理器,请实现此接口并覆盖其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("https://tutorialspoint.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>
<!--[if IE 8]><html class = "ie ie8"> <![endif]-->
<!--[if IE 9]><html class = "ie ie9"> <![endif]-->
<!--[if gt IE 9]><!-->
<html lang = "en-US"> <!--<![endif]-->
<head>
<!-- Basic -->
<meta charset = "utf-8">
<meta http-equiv = "X-UA-Compatible" content = "IE = edge">
<meta name = "viewport" content = "width = device-width,initial-scale = 1.0,userscalable = yes">
<link href = "https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css"
rel = "stylesheet" type = "text/css" />
<link rel = "stylesheet" href = "/questions/css/home.css?v = 3" />
<script src = "/questions/js/jquery.min.js"></script>
<script src = "/questions/js/fontawesome.js"></script>
<script src = "https://cdn.muicss.com/mui-0.9.39/js/mui.min.js"></script>
</head>
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-232293-17');
</script>
</body>
广告