HttpClient

HttpClient

HttpClient:用于服务和服务之间接口调用

package http;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.util.EntityUtils;
import org.springframework.stereotype.Component;

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

/**
 * @author LiJinSong
 * @create 2021-06-24
 */
@Slf4j
@Component
public class HttpClient {

    /**
     * 使用HttpClient 调用远程接口
     * @param ip 远程服务ip
     * @param port 远程服务端口号
     * @param interfaceName 接口名称
     * @param params 参数
     * @return 结果如果为空,说明调用报错;不为空,则可以获取到json数据
     */
    public static JSONObject doGet(String ip, Integer port , String interfaceName, Map<String,String> params){
        // 1、拼接URL
        StringBuffer url = new StringBuffer();
        url.append("http://");
        url.append(ip);
        url.append(":");
        url.append(port);
        url.append(interfaceName);

        // 2、解析get请求后的参数
        StringBuilder param = new StringBuilder();
        if (!params.isEmpty()) {
            for (String key : params.keySet()) {
                String value = params.get(key);
                param.append(key).append("=").append(value).append("&");
            }
        }

        if(StringUtils.isNotBlank(param)){
            param = new StringBuilder(param.substring(0, param.length()-1));
            url.append("?").append(param);
        }

        log.info("=====> start HttpClient 创建接口调用请求 URL:{}",url.toString());

        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        // 3、创建Get请求
        HttpGet http = new HttpGet(url.toString());

        try {
            response = client.execute(http);
            int statusCode = response.getStatusLine().getStatusCode();
            String result = EntityUtils.toString(response.getEntity(), "UTF-8");

            if(200 == statusCode && StringUtils.isNotBlank(result)){
                return JSONObject.parseObject(result);
            }

            log.error("=====> end 远程服务接口调用失败 ===> 响应状态码:{},响应数据:{}",statusCode,result);
            return null;
        } catch (IOException e) {
            log.error("=====> end 远程服务接口调用失败 ===> 异常信息:{}",e.getMessage());
        }finally {
            if(response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("=====> end 关闭response失败 ===> 异常信息:{}",e.getMessage());
                }
            }
            if(client != null){
                try {
                    client.close();
                } catch (IOException e) {
                    log.error("=====> end 关闭client失败 ===> 异常信息:{} end",e.getMessage());
                }
            }
        }
        return null;
    }
}

遇到的问题

在进行URL封装时,如果URL中有空格、时间等数据,则需要进行URL的转换,否则会报java.lang.IllegalArgumentException: Illegal character in query at index。

例如:

String url = baseUrl + "?" + "name=" + name + "&time=2020-06-13 14:52:23";

url = url.replaceAll(" ", "%20").replaceAll(":", "%3A");

特殊的参数及转换:

%3F

&       %26

|       %124

=       %3D

#       %23

/       %2F

+       %2B
 
%       %25

:       %3A

空格    %20
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值