HttpClient 发送 get、post 请求

HttpClient 介绍

HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

HttpClient是客户端的http通信实现库,这个类库的作用是接收和发送http报文

 添加Maven依赖

       <!--****** httpclient start ******-->
       <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
        <!--****** httpclient end******-->

        <!--LMGD-注:这个依赖可选-->
	    <dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpasyncclient</artifactId>
			<version>4.0.1</version>
		 </dependency>
      <!-- fastjson json-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.1.40</version>
		</dependency>

 HttpClient 发送 get、post 请求

注意:HttpClient 发送 post 请求时有三种格式报文的请求,分别是application/x-www-form-urlencoded、application/json、text/xml 格式报文的请求;本文例子写的是处理 application/json 格式报文的请求。

HttpclientUtils 工具类编写

package com.wondersgroup.hs.jw.jwxt.utils;


import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author 邓林妹
 * @date 2022/4/21
 */
public class HttpclientUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpclientUtils.class);

    /**
     * get 方式调用
     *
     * @param url
     * @return
     */
    public static String get(String url) {
        logger.info("=====================HTTP GET 请求参数 url=" + url);
        InputStream is = null;
        String body = null;
        StringBuilder res = new StringBuilder();
        // 实例化CloseableHttpClient
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            // 添加URL和请求参数
           //替换空格;get请求,url拼接参数时,参数值可能存在空格,需要对空格做处理,不然接口会调不通
            url = url.replaceAll(" ", "%20");
            URIBuilder ub = new URIBuilder(url);
            // 使用get方法添加URL
            HttpGet get = new HttpGet(ub.build());
            // 设置请求超时时间
            RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).build();
            get.setConfig(config);
            //使用http调用远程,获取相应信息
            response = client.execute(get);
            // 获取响应状态码,可根据是否响应正常来判断是否需要进行下一步
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                return "请求失败 statusCode=" + statusCode;
            }
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            // 读取响应内容
            if (entity != null) {
                is = entity.getContent();
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((body = br.readLine()) != null) {
                    res.append(body);
                }
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        logger.info("=====================HTTP GET 请求响应参数 result=" + res.toString());
        return res.toString();
    }

    /**
     * 通过post方式调用http接口
     *
     * @param url       url路径
     * @param jsonParam json格式的参数
     * @return
     * @throws Exception
     */
    public static String post(String url, String jsonParam) {
        logger.info("=====================HTTP POST 请求参数 【url=" + url + ",jsonParam=" + jsonParam + "】");
        //声明返回结果
        String result = "";
        //开始请求API接口时间
        long startTime = System.currentTimeMillis();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;
        HttpClient httpClient = null;
        try {
            // 创建连接
            httpClient = HttpClientFactory.getInstance().getHttpClient();
            // 设置请求头和报文
            HttpPost httpPost = HttpClientFactory.getInstance().httpPost(url);
            Header header = new BasicHeader("Accept-Encoding", null);
            httpPost.setHeader(header);
            // 设置报文和通讯格式
            StringEntity stringEntity = new StringEntity(jsonParam, HttpConstant.UTF8_ENCODE);
            stringEntity.setContentEncoding(HttpConstant.UTF8_ENCODE);
            stringEntity.setContentType(HttpConstant.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);
            //log.info("请求{}接口的参数为{}", url, jsonParam);
            //执行发送,获取相应结果
            httpResponse = httpClient.execute(httpPost);
            httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);
            long endTime = System.currentTimeMillis();

            logger.info("HTTP POST 请求响应时间 httpResponse time=" + new java.util.Date(startTime - endTime));
        } catch (Exception e) {
            logger.info("http post 请求异常");
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(httpEntity);
            } catch (IOException e) {
                throw new RuntimeException("http请求释放资源异常");
            }
        }
        logger.info("=====================HTTP POST 请求响应参数 result=" + result);
        return result;
    }
}
HttpclientUtils 工具类 post 请求,用到的其他相关类编写:(如果只是使用get方式调用的话,不需要这些类,这两个都是 post 请求会用的类)
package com.wondersgroup.hs.jw.jwxt.utils;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import javax.net.ssl.SSLContext;
import java.security.NoSuchAlgorithmException;

/**
 * @author 邓林妹
 * @date 2022/4/22
 */
public class HttpClientFactory {

    private static HttpClientFactory instance = null;

    private HttpClientFactory() {
    }

    public synchronized static HttpClientFactory getInstance() {
        if (instance == null) {
            instance = new HttpClientFactory();
        }
        return instance;
    }


    public synchronized HttpClient getHttpClient() {
        HttpClient httpClient = null;
        if (HttpConstant.IS_KEEP_ALIVE) {
            //获取长连接
            httpClient = new KeepAliveHttpClientBuilder().getKeepAliveHttpClient();
        } else {
            // 获取短连接
            httpClient = new HttpClientBuilder().getHttpClient();
        }
        return httpClient;
    }

    public HttpPost httpPost(String httpUrl) {
        HttpPost httpPost = null;
        httpPost = new HttpPost(httpUrl);
        if (HttpConstant.IS_KEEP_ALIVE) {
            // 设置为长连接,服务端判断有此参数就不关闭连接。
            httpPost.setHeader("Connection", "Keep-Alive");
        }
        return httpPost;
    }


    private static class KeepAliveHttpClientBuilder {

        private static HttpClient httpClient;

        /**
         * 获取http长连接
         */
        private synchronized HttpClient getKeepAliveHttpClient() {
            if (httpClient == null) {
                LayeredConnectionSocketFactory sslsf = null;
                try {
                    sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }

                Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                        .<ConnectionSocketFactory>create().register("https", sslsf)
                        .register("http", new PlainConnectionSocketFactory()).build();
                PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
                cm.setMaxTotal(HttpConstant.MAX_TOTAL);
                cm.setDefaultMaxPerRoute(HttpConstant.MAX_CONN_PER_ROUTE);

                RequestConfig requestConfig = RequestConfig.custom()
                        .setConnectTimeout(HttpConstant.CONNECT_TIMEOUT)
                        .setSocketTimeout(HttpConstant.SOCKET_TIMEOUT).build();
                // 创建连接
                httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(cm).build();
            }

            return httpClient;
        }
    }


    private static class HttpClientBuilder {
        private HttpClient httpClient;

        /**
         * 获取http短连接
         */
        private synchronized HttpClient getHttpClient() {
            if (httpClient == null) {
                RequestConfig requestConfig = RequestConfig.custom()
                        // 设置请求超时时间
                        .setConnectTimeout(HttpConstant.CONNECT_TIMEOUT)
                        // 设置响应超时时间
                        .setSocketTimeout(HttpConstant.SOCKET_TIMEOUT).build();
                // 创建连接
                httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
            }
            return httpClient;
        }
    }
}
package com.wondersgroup.hs.jw.jwxt.utils;

/**
 * HttpClient请求常量类
 *
 * @author 邓林妹
 * @date 2022/4/22
 */
public class HttpConstant {

    /**
     * httpClient连接超时时间,单位毫秒
     */
    public static final int CONNECT_TIMEOUT = 3 * 1000;

    /**
     * httpClient请求获取数据的超时时间(即响应时间) 单位毫秒
     */
    public static final int SOCKET_TIMEOUT = 10 * 1000;

    /**
     * http连接池大小
     */
    public static final int MAX_TOTAL = 10;

    /**
     * 分配给同一个route(路由)最大的并发连接数
     */
    public static final int MAX_CONN_PER_ROUTE = 2;

    /**
     * http连接是否是长连接
     */
    public static final boolean IS_KEEP_ALIVE = true;

    /**
     * 调用接口失败默认重新调用次数
     */
    public static final int REQ_TIMES = 3;

    /**
     * utf-8编码
     */
    public static final String UTF8_ENCODE = "UTF-8";

    /**
     * application/json
     */
    public static final String APPLICATION_JSON = "application/json";

    /**
     * text/xml
     */
    public static final String TEXT_XML = "text/xml";

}

 Controller 层编写

/**
 * @author 邓林妹
 * @date 2022/4/24
 */
@RestController
@RequestMapping("/test")
public class HttpClientTest {

    @RequestMapping("/get")
    @ResponseBody
    public BaseResponse getRequest(@RequestBody RequestParamDto dto) {
        try {
            String message = HttpclientUtils.get(dto.getUrl());
            return BaseResponse.returnSuccess(message);
        } catch (Exception e) {
            return BaseResponse.returnFault(e.getMessage());
        }
    }

    @RequestMapping("/post")
    @ResponseBody
    public BaseResponse postRequest(@RequestBody RequestParamDto dto) {
        try {
            String message = HttpclientUtils.post(dto.getUrl(), JSON.toJSONString(dto.getPerson()));
            return BaseResponse.returnSuccess(message);
        } catch (Exception e) {
            return BaseResponse.returnFault(e.getMessage());
        }
    }
}

相关实体类编写: 

/**
 * @author 邓林妹
 * @date 2022/4/24
 */
public class RequestParamDto {

    private String url;
    private Person person;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
}
/**
 * @author 邓林妹
 * @date 2022/4/24
 */
public class Person {

    private String idCardNo;
    private String examCode;

    public String getIdCardNo() {
        return idCardNo;
    }

    public void setIdCardNo(String idCardNo) {
        this.idCardNo = idCardNo;
    }

    public String getExamCode() {
        return examCode;
    }

    public void setExamCode(String examCode) {
        this.examCode = examCode;
    }
}

测试- HttpClient 发送get、post请求

调用Controller层的接口地址(可以是get/post请求),传入 url (get、post 请求的url),通过 url  ,HttpClient 向服务器端发送 get、post请求。

高德地图-IP定位-get 请求接口地址:

https://restapi.amap.com/v3/ip?ip=114.247.50.2&output=xml&key=<用户的key>

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值