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.tw/");
//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>
廣告