【Httpclient】 简单使用

package com.peko.demo;

import com.peko.demo.utils.HttpUtils;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class Test01 {

    /**
     * HttpClient 发起 get 请求
     * @throws IOException
     */
    @Test
    public void test01() throws IOException {
        //1、创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2、创建HttpGet请求并进行相关设置
        HttpGet httpGet = new HttpGet("网站url");
        httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.47");
        //3、发起请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //4、获取响应数据
        if(response.getStatusLine().getStatusCode() == 200){
            String html = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(html);
        }
        //5、关闭资源
        httpClient.close();
        response.close();
    }

    /**
     * HttpClient 发起 post 请求
     * @throws IOException
     */
    @Test
    public void test02() throws IOException {
        //1、创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2、创建HttpPost请求并进行相关设置
        HttpPost httpPost = new HttpPost("网站url");
        //准备参数
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("username","xx"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
        httpPost.setEntity(entity);
        httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.47");
        //3、发起请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        //4、获取响应数据
        if(response.getStatusLine().getStatusCode() == 200){
            String html = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(html);
        }
        //5、关闭资源
        httpClient.close();
        response.close();
    }

    /**
     * HttpClient 连接池
     * @throws IOException
     */
    @Test
    public void test03() throws IOException {
        //1、创建HttpClient连接管理器
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        //2、设置参数
        cm.setMaxTotal(200);  //最大连接数
        cm.setDefaultMaxPerRoute(20);  //每个主机的最大并发
        doGet(cm);
    }

    private void doGet(PoolingHttpClientConnectionManager cm) throws IOException {
        //3、获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
        //4、创建HttpGet请求并进行相关设置
        HttpGet httpGet = new HttpGet("网站url");
        httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.47");
        //5、发送请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //6、获取数据
        if(response.getStatusLine().getStatusCode() == 200){
            String html = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(html);
        }
        //7、关闭资源
        response.close();
        //这里就不用关闭 httpClient ,因为httpClient使用完毕之后会归还到连接池
    }

    /**
     * HttpClient 设置代理
     * @throws IOException
     */
    @Test
    public void test04() throws IOException {

        //0、创建请求配置对象
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(10000) //设置连接超时时间
                .setConnectTimeout(10000) //设置创建连接超时时间
                .setConnectionRequestTimeout(10000) //设置请求超时时间
//                .setProxy()  设置代理服务器
                .build();

        //1、创建 HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        //2、创建HttpGet请求并进行相关设置
        HttpGet httpGet = new HttpGet("网站url");
        httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.47");
        //3、发起请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //4、获取响应数据
        if(response.getStatusLine().getStatusCode() == 200){
            String html = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(html);
        }
        //5、关闭资源
        httpClient.close();
        response.close();
    }
}

UrlEncodedFormEntity 和 StringEntity 的区别:

HTTPClient进行body传参,要使用StringEntity,而不要使用UrlEncodedFormEntity 

原因:UrlEncodedFormEntity会以字符串键值对形式传给后台,即:{"a":"value1", "b":"value2"},传给java方法,接收到的参数是:a=value1&b=value2,即它不支持json参数传递;

而StringEntity传参,后台接收到的依然是 {"a":"value1", "b":"value2"},即StringEntity能传递json,当然,如果你传递的就是一个普通的字符串,StringEntity也是支持的。

StringEntity进行json传参,对方可以解析request获取参数,如果对方以单个参数接收则用UrlEncodedFormEntity
————————————————
原文链接:https://blog.csdn.net/menggudaoke/article/details/90378348

封装工具类

package com.peko.demo.utils;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
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.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map.Entry;

import java.util.*;

/**
 * 封装 HttpClient 工具类
 */
public abstract class HttpUtils {
    /**
     * 连接池
     */
    private static PoolingHttpClientConnectionManager cm;

    /**
     * 请求头
     */
    private static Map<String,String> headerMap = null;

    /**
     * 请求配置
     */
    private static RequestConfig config = null;

    static {
        cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(200);
        cm.setDefaultMaxPerRoute(20);

        config = RequestConfig.custom()
                .setSocketTimeout(10000) //设置连接超时时间
                .setConnectTimeout(10000) //设置创建连接超时时间
                .setConnectionRequestTimeout(10000) //设置请求超时时间
                .build();

        headerMap = new HashMap<>();
        headerMap.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.47");
    }

    public static String getHtml(String url){
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
        HttpGet httpGet = new HttpGet(url);
        //放进所有请求头
        Set<Entry<String, String>> entrySet = headerMap.entrySet();
        for (Entry<String, String> o : entrySet) {
            httpGet.setHeader(o.getKey(),o.getValue());
        }

        CloseableHttpResponse response = null;
        String html = null;
        try{
            response = httpClient.execute(httpGet);

            if(response.getStatusLine().getStatusCode() == 200){
                if(response.getEntity() != null){
                    html = EntityUtils.toString(response.getEntity(), "UTF-8");
                    System.out.println(html);
                }
            }

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                response.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }

        return html;
    }

    public static void main(String[] args) {
        HttpUtils.getHtml("网站url");
    }
}

案例 

 public String post(User user){

        String url = "";
        String date = "";
        String result = "";

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);
        //设置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(2000).setConnectionRequestTimeout(1000)
                .setSocketTimeout(2000).build();
        httpPost.setConfig(requestConfig);

        try{
            // 这里用到fastJson的包
            date = JSON.toJSONString(user);
            logger.info(date);

            StringEntity entity = new StringEntity(date, "UTF-8");

            // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
            httpPost.setEntity(entity);

            httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        }catch (Exception e){
            logger.warn("数据错误");
        }

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            logger.info("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                logger.info("响应内容长度为:" + responseEntity.getContentLength());
                //【坑】同一个httpclient中只能有一个获取entity的方法
                result = EntityUtils.toString(responseEntity);
            }
        } catch (ClientProtocolException | ParseException e) {
            logger.warn(e.getMessage());
        } catch (IOException e) {
            logger.warn(e.getMessage());
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                logger.warn(e.getMessage());
            }
        }

        return result;
    }

【坑】同一个httpclient中只能有一个获取entity的方法,就是说,如果不保存entity()的值,再读一次是无法读到的!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值