运用HttpClient调用其它项目的接口

简介: 运用HttpClient调用其它项目的接口

首先引入依赖

 <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.6</version>
    </dependency>
private final int timeOut = 500;public String queryString(String code) {
        // 获得Http客户端(可以理解为:先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 参数
        StringBuffer params = new StringBuffer();
        try {
            // 字符数据最好encoding下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
            params.append("code=" + URLEncoder.encode(code, "utf-8"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        // 创建Get请求
        HttpGet httpGet = new HttpGet(192.168.xx.xx:port/xx/queryString);
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(timeOut)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(timeOut)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(timeOut)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();
            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
                String json = EntityUtils.toString(responseEntity);
                String result = JsonUtil.fromJson(json, String.class);
                if(null!= result ){
                    return result ;
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            //todo 此处做异常处理返回
            //e.printStackTrace();return ("与数据服务连接异常!");
        } finally {
            closeClient(httpClient, response);
        }
        return null;
    }
相关文章
|
7月前
|
Apache
HttpClient实现RPC调用
HttpClient实现RPC调用
25 0
|
2月前
|
Java Apache
远程调用工具HttpClient工具类封装
java远程调用工具HttpClient工具类类封装
|
2月前
封装httpclient工具类
httpclient远程调用工具封装使用
|
7月前
|
网络协议 Linux Apache
httpClient调用失败和配置优化
httpClient调用失败和配置优化
90 0
|
消息中间件 JavaScript 小程序
OkHttp完美封装,一行搞完外部请求
OkHttp完美封装,一行搞完外部请求
Java HttpClient 如何使用代理IP请求接口
Java HttpClient 如何使用代理IP请求接口