Apache HttpClient - Response 响应处理程序

建议使用Response 响应处理程序处理 HTTP 响应。 在本章中,我们将讨论如何创建Response 响应处理程序以及如何使用它们来处理响应。

如果您使用Response 响应处理程序,所有 HTTP 连接将自动释放。


创建Response 响应处理程序

HttpClient API 在 org.apache.http.client. 包中提供了一个称为 ResponseHandler 的接口。为了创建Response 响应处理程序,请实现该接口并覆盖其 handleResponse() 方法。

每个响应都有一个状态码,如果状态码在 200 到 300 之间,则表示该操作已成功接收、理解和接受。 因此,在我们的示例中,我们将使用此类状态代码处理响应的实体。


使用Response 响应处理程序执行请求

按照下面给出的步骤使用Response 响应处理程序执行请求。


步骤 1 - 创建一个 HttpClient 对象

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

CloseableHttpClient httpclient = HttpClients.createDefault();

步骤 2 - 实例化Response 响应处理程序

使用以下代码行实例化上面创建的Response 响应处理程序对象 −

ResponseHandler<String> responseHandler = new MyResponseHandler(); 

步骤 3 - 创建一个 HttpGet 对象

HttpGet 类表示 HTTP GET 请求,该请求使用 URI 检索给定服务器的信息。

通过实例化 HttpGet 类并将表示 URI 的字符串作为参数传递给其构造函数来创建 HttpGet 请求。

ResponseHandler<String> responseHandler = new MyResponseHandler(); 

步骤 4 - 使用Response 响应处理程序执行 Get 请求

CloseableHttpClient 类有一个execute() 方法的变体,它接受两个对象ResponseHandler 和HttpUriRequest,并返回一个响应对象。

String httpResponse = httpclient.execute(httpget, responseHandler);

示例

以下示例演示了Response 响应处理程序的用法。

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.w3schools.cn/");

      //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>