Apache HttpClient

Posted tractors

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Apache HttpClient相关的知识,希望对你有一定的参考价值。

一、Apache HttpClient:

  HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 htmlUnit 都使用了 HttpClient。

二、Apache HttpClient 使用流程:

  • 创建 HttpClient 对象。

  • 创建请求方法的实例,并指定请求 URL。如果需要发送 GET 请求,创建 HttpGet 对象;如果需要发送 POST 请求,创建 HttpPost 对象。

  • 如果需要发送请求参数,可调用 HttpGetHttpPost 共同的 setParams(HttpParams params) 方法来添加请求参数;对于 HttpPost 对象而言,也可调用 setEntity(HttpEntity entity) 方法来设置请求参数。

  • 调用 HttpClient 对象的 execute(HttpUriRequest request) 发送请求,该方法返回一个 HttpResponse

  • 调用 HttpResponsegetAllHeaders()getHeaders(String name) 等方法可获取服务器的响应头;调用 HttpResponsegetEntity() 方法可获取 HttpEntity 对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

  • 释放连接。无论执行方法是否成功,都必须释放连接

三、示例:

(1)依赖:

技术图片
        <!-- Apache Http Begin -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>fluent-hc</artifactId>
            <version>4.5.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.5</version>
        </dependency>
        <!-- Apache Http End -->
pom.xml

(2)测试:

public class HttpClientTest 
    public static void main(String[] args) 
        get();
    
    private static void get() 
        // 创建 HttpClient 客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建 HttpGet 请求
        HttpGet httpGet = new HttpGet("http://www.baidu.com");
        // 设置长连接
        httpGet.setHeader("Connection", "keep-alive");
        // 设置代理(模拟浏览器版本)
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
        // 设置 Cookie
        httpGet.setHeader("Cookie", "UM_distinctid=16442706a09352-0376059833914f-3c604504-1fa400-16442706a0b345; CNZZDATA1262458286=1603637673-1530123020-%7C1530123020; JSESSIONID=805587506F1594AE02DC45845A7216A4");

        CloseableHttpResponse httpResponse = null;
        try 
            // 请求并获得响应结果
            httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            // 输出请求结果
            System.out.println(EntityUtils.toString(httpEntity));
         catch (IOException e) 
            e.printStackTrace();
        

        // 无论如何必须关闭连接
        finally 
            if (httpResponse != null) 
                try 
                    httpResponse.close();
                 catch (IOException e) 
                    e.printStackTrace();
                
            
            if (httpClient != null) 
                try 
                    httpClient.close();
                 catch (IOException e) 
                    e.printStackTrace();
                
            
        
    

四、工具类:

技术图片
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Arrays;

/**
 * HttpClient工具类
 */
public class HttpClientUtils 
    private static final String REQUEST_METHOD_GET = "GET";
    private static final String REQUEST_METHOD_POST = "POST";
    private static final String REQUEST_HEADER_CONNECTION = "keep-alive";
    private static final String REQUEST_HEADER_USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";

    /**
     * Get请求
     *
     * @param url 路径
     * @return 字符串
     */
    public static String doGet(String url) 
        String result = HttpClientUtils.getResult("GET", url, null);
        return result;
    

    /**
     * GET请求
     *
     * @param url    API
     * @param cookie cookie
     * @return json字符串
     */
    public static String doGet(String url, String cookie) 
        String result = HttpClientUtils.getResult("GET", url, cookie);
        return result;
    

    /**
     * POST请求
     *
     * @param url
     * @param params 请求参数
     * @return json字符串
     */
    public static String doPost(String url, BasicNameValuePair... params) 
        String result = HttpClientUtils.getResult("POST", url, null, params);
        return result;
    

    /**
     * POST请求
     *
     * @param url
     * @param cookie
     * @param params 请求参数
     * @return json字符串
     */
    public static String doPost(String url, String cookie, BasicNameValuePair... params) 
        String result = HttpClientUtils.getResult("POST", url, cookie, params);
        return result;
    


    /**
     * 使用HttpClient通过API请求来获得json字符串
     *
     * @param requestMethod 请求方式
     * @param url           请求路径
     * @param cookie        cookie
     * @param params        请求参数
     * @return json字符串
     */
    private static String getResult(String requestMethod, String url, String cookie, BasicNameValuePair... params) 
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        String result = null;
        try 
            //GET
            if (requestMethod.equals(HttpClientUtils.REQUEST_METHOD_GET)) 
                HttpGet httpGet = new HttpGet(url);
                httpGet.setHeader("Connection", HttpClientUtils.REQUEST_HEADER_CONNECTION);
                httpGet.setHeader("Cookie", cookie);
                httpGet.setHeader("User-Agent", HttpClientUtils.REQUEST_HEADER_USER_AGENT);
                httpResponse = httpClient.execute(httpGet);
            

            //POST
            else if (requestMethod.equals(HttpClientUtils.REQUEST_METHOD_POST)) 
                HttpPost httpPost = new HttpPost(url);
                httpPost.setHeader("Connection", HttpClientUtils.REQUEST_HEADER_CONNECTION);
                httpPost.setHeader("Cookie", cookie);
                httpPost.setHeader("User-Agent", HttpClientUtils.REQUEST_HEADER_USER_AGENT);
                httpPost.setEntity(new UrlEncodedFormEntity(Arrays.asList(params)));
                httpResponse = httpClient.execute(httpPost);
            
            //----

            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
         catch (IOException e) 
            e.printStackTrace();
         finally 
            if (httpClient != null) 
                try 
                    httpClient.close();
                 catch (IOException e) 
                    e.printStackTrace();
                
            
        
        return result;
    
HttpClientUtils

 

以上是关于Apache HttpClient的主要内容,如果未能解决你的问题,请参考以下文章

Apache 服务

我怎么在LINUX下查看apache日志

Linux中怎样启动apache服务

启动apache时出现xampp错误说停止apache

如何解决 apache htacess 不生效

如何在Linux下搭建apache服务器