HttpClient系列(二),Apache HttpClient

目录



正文


Apache HttpClient曾经最火的Http Client框架。不光在Java服务端,甚至Android都使用它。后来OkHttp和SpringRestTemplate流行起来后就被用的越来越少了。

这是一个很好的框架,官方文档还是很友好的,先以GET请求为例,笔者从官方抄写了一段代码放到一个新建的ApacheHttpUtil类里面:

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;

import java.io.IOException;

public class ApacheHttpUtil {
    private ApacheHttpUtil() {}

    public static String get(String urlStr) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpget = new HttpGet(urlStr);
            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 {
                        throw new ClientProtocolException("Unexpected response status: " + status);
                    }
                }
            };
            return httpclient.execute(httpget, responseHandler);
        } finally {
            httpclient.close();
        }
    }
}

然后在main方法里面编写测试代码

String content = ApacheHttpUtil.get("http://www.baidu.com");
System.out.println(content);

运行结果输出正常,没有问题。这就是Apache HttpClient创建的GET请求。

接着再看POST请求是怎么创建的。跟着笔者在ApacheHttpUtill类里面,再创建一个post方法,内容如下:

public static String post(String urlStr, String params) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(urlStr);
        StringEntity entity = new StringEntity(params);
        entity.setContentType(ContentType.APPLICATION_FORM_URLENCODED.toString());
        httppost.setEntity(entity);
        System.out.println("Executing request: " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            return EntityUtils.toString(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

这个post方法,用于模拟表单提交。请看测试代码和测试结果。

String fromData = "page=1&count=5";
String content = ApacheHttpUtil.post("https://api.apiopen.top/getWangYiNews", fromData);
System.out.println(content);

特别要注意的是,需要设置好entity的ContentType类型,否则会导致参数传递失败。

这里在延伸一个新问题,如果请求需要校验header中的token怎么办?很简单,只要用HttpGet或者HttpPost的实例调用addHeader方法就可以了。例如:

httppost.addHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9");

如果想深入Apache HttpClient,了解更多的用法可以看看官方的例子:http://hc.apache.org/httpcomponents-client-ga/examples.html

源代码地址:https://gitee.com/dev-tang/httpclient-demo.git

本博客采用 知识共享署名-禁止演绎 4.0 国际许可协议 进行许可

本文标题:HttpClient系列(二),Apache HttpClient

本文地址:https://dev-tang.com/post/2020/05/httpclient-apache.html

推荐阅读