集册 Java实例教程 使用ResponseHandler简化处理HTTP响应和释放相关资源。

使用ResponseHandler简化处理HTTP响应和释放相关资源。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

1097
使用ResponseHandler简化对HTTP响应的处理并释放关联的资源。


import java.io.IOException;
/**
来 自 n o w j a   v  a . c o m - 时  代  Java
**/

import java.util.Properties;


import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.ClientProtocolException;

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;


/**

 * This example demonstrates the use of the {@link ResponseHandler} to simplify

 * the process of processing the HTTP response and releasing associated resources.

 */

public class Main {


    public final static void main(String[] args) throws Exception {




        CloseableHttpClient httpclient = HttpClients.createDefault();/* 来自 时代Java - nowjava.com*/


        try {


            HttpGet httpget = new HttpGet("https://your host");


            System.out.println("Executing request "

                    + httpget.getRequestLine());


            // Create a custom response handler

            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {


                @Override

                public String handleResponse(final HttpResponse response)

                        throws ClientProtocolException, IOException {

                    int status = response.getStatusLine().getStatusCode();

                    if (status >= 200 && status < 300) {

                        HttpEntity entity = response.getEntity();

                        return entity != null ? EntityUtils

                                .toString(entity) : null;

                    } else {

                        
展开阅读全文