使用Apache提供的HttpClient对象调用HTTP接口(基于GET请求)

本篇将主要介绍如何使用HttpClient4.5版本调用本地普通、restful接口的实例.(实现代码中有大量注释供理解所用)

先准备好一个Springboot项目,方便自己编写接口与后台直接main方法调用.

Springboot工程结构展示:

Springboot工程最终结构图

准备好后,第一步引入Apache提供的HttpClient4.5版本的依赖包.

依赖如下:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version>
</dependency>

引入好依赖包后,第二步我们先简单的在Controller层中编写两个不同类型的GET方法接口.

一个是普通的GET方法接口,简易代码如下:

@ResponseBody
@RequestMapping(value = "/user/msg",method = {RequestMethod.GET})
public String getUserMsg(@RequestParam("id")int id){
   System.out.println("GET请求需要获取Id为"+id+"的用户...");
   return "GET请求需要获取Id为"+id+"的用户...";
}

另一个是restful的GET方法接口,简易代码如下:

@ResponseBody
@RequestMapping(value = "/user/{id}",method = {RequestMethod.GET})
public String getUserMsgRestful(@PathVariable("id")int id){
   System.out.println("GET请求需要获取Id为"+id+"的用户...");
   return "GET请求需要获取Id为"+id+"的用户...";
}

接口创建好后,启动Springboot项目,在浏览器上测试下接口

测试结果如下:

普通Get方法接口测试结果

restfulGET方法接口测试结果

接口验证可用后,第三步便是编写HttpClientUtil工具类,然后直接main方法调用两种接口即可.

    /**
     * 使用HttpClient4.5版本对指定接口路径发送GET请求
     * @param httpUrl   指定接口路径
     * @param params    接口路径需要携带的参数集
     * @return  接口返回的消息
     */
    public static String doGet(String httpUrl,Map<String,Object> params){
        String result = null;
        //声明httpClient,httpResponse于try...catch语句外.方便最后关闭资源
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try{
            //创建一个连接实例
            httpClient = HttpClients.createDefault();
            //GET请求参数需要拼接到URL地址后
            if(!params.isEmpty()){
                //获取Map集合中的键集合
                Set<String> keySet = params.keySet();
                Iterator iterator = keySet.iterator();
                StringBuffer stringBuffer = new StringBuffer();
                //迭代器遍历URL需要携带的参数
                //并根据接口类型进行拼接URL地址
                while(iterator.hasNext()){
                    String key = (String)iterator.next();
                    String value = params.get(key).toString();
                    // 1.普通Get接口拼接参数方式:url?key1=value1&key2=value2
                    if(stringBuffer.toString().equals("")){
                        stringBuffer.append("?");
                    } else {
                        stringBuffer.append("&");
                    }
                    stringBuffer.append(key);
                    stringBuffer.append("=");
                    stringBuffer.append(value);
                    /* 2.restful接口拼接参数方式:url/{param1}/{param2}
                    stringBuffer.append("/");
                    stringBuffer.append(value); */
                }
                httpUrl += stringBuffer.toString();
                System.out.println("GET请求地址展示:"+httpUrl);
            }
            //将接口地址封装到HttpGet对象中
            HttpGet httpGet = new HttpGet(httpUrl);
            //调用指定接口,并获取response响应对象
            httpResponse = httpClient.execute(httpGet);
            //HTTP-200状态码表示请求已成功
            if(httpResponse.getStatusLine().getStatusCode()==200){
                result = EntityUtils.toString(httpResponse.getEntity());
            }
        } catch(Exception e){
            e.printStackTrace();
        } finally {
            //逐一关闭使用过的资源,释放内存
            try{
                if(httpResponse!=null){
                    httpResponse.close();
                }
                if(httpClient!=null){
                    httpClient.close();
                }
            } catch(Exception e){
                e.printStackTrace();
            }
        }
        return result;
    }

注意此处!由于访问普通接口和访问restful接口携带参数的方式不同,所以需要编写两种URL拼接方式.

                while(iterator.hasNext()){
                    String key = (String)iterator.next();
                    String value = params.get(key).toString();
                    /* 1.普通Get接口拼接参数方式:url?key1=value1&key2=value2
                    if(stringBuffer.toString().equals("")){
                        stringBuffer.append("?");
                    } else {
                        stringBuffer.append("&");
                    }
                    stringBuffer.append(key);
                    stringBuffer.append("=");
                    stringBuffer.append(value);*/
                    // 2.restful接口拼接参数方式:url/{param1}/{param2}
                    stringBuffer.append("/");
                    stringBuffer.append(value);
                }

第四步,便可以在HttpClientUtil工具类main方法中调用doGet方法.访问两种接口.

1. 调用普通接口

public static void main(String[] args) {
        Map<String,Object> params = new HashMap<>();
        params.put("id",1);
        System.out.println(HttpClientUtil.doGet("http://127.0.0.1:8080/user/msg",params));
    }

调用结果如下图:

main程序输出返回值如下:

Springboot接口输出结果如下:

2.调用restful接口

public static void main(String[] args) {
        Map<String,Object> params = new HashMap<>();
        params.put("id",1);
        System.out.println(HttpClientUtil.doGet("http://127.0.0.1:8080/user",params));
    }

调用结果如下图:

main程序输出返回值如下:

Springboot接口输出结果如下:

以上便完成了使用HttpClient对象向普通和restful接口发送GET请求的任务

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值