httpclient调用远程接口的方法


Posted in Java/Android onAugust 14, 2022

本文实例为大家分享了httpclient调用远程接口的具体代码,供大家参考,具体内容如下

依赖jar包 httpclient:4.5.6.jar httpcore:4.4.3

封装HttpClient接口

package com.example.HttpClient;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//需要引入的jar包
//compile('org.apache.httpcomponents:httpclient:4.5.6')
//compile('org.apache.httpcomponents:httpcore:4.4.3')

/**
 * @program: webservice_demo
 * @description: HttpClient工具类
 * @author: miaoqixin
 * @create: 2018-11-28 16:39
 **/
public class HttpClientUtil {

    private CloseableHttpClient httpClient;

    public HttpClientUtil() {
        // 1 创建HttpClinet,相当于打开浏览器
        httpClient = HttpClients.createDefault();
    }

    /* *
     * get请求
     * @author miaoqixin
     * @date 2018/11/28 16:51
     * @param [url, map]
     * @return HttpResult
     */
    public HttpResult doGet(String url, Map<String, Object> map) throws Exception {

        // 声明URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);

        // 判断参数map是否为非空
        if (map != null) {
            // 遍历参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 设置参数
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 2 创建httpGet对象,相当于设置url请求地址
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // 3 使用HttpClient执行httpGet,相当于按回车,发起请求
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
        } catch (IOException e) {
            HttpResult httpResult = new HttpResult();
            httpResult.setCode(404);
            httpResult.setBody("请求失败");
            return httpResult;
        }

        // 4 解析结果,封装返回对象httpResult,相当于显示相应的结果
        // 状态码
        // response.getStatusLine().getStatusCode();
        // 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
        // EntityUtils.toString(response.getEntity(), "UTF-8");
        HttpResult httpResult = new HttpResult();
        // 解析数据封装HttpResult
        if (response.getEntity() != null) {
            //httpResult = new HttpResult(response.getStatusLine().getStatusCode(),EntityUtils.toString(response.getEntity(),"UTF-8"));
            httpResult.setCode(response.getStatusLine().getStatusCode());
            httpResult.setBody(EntityUtils.toString(response.getEntity(),"UTF-8"));

        } else {
            //httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
            httpResult.setCode(response.getStatusLine().getStatusCode());
            //httpResult.setBody("");
        }

        // 返回
        return httpResult;
    }

    /* *
     * post请求
     * @author miaoqixin
     * @date 2018/11/28 18:13
     * @param [url, map]
     * @return com.example.HttpClient.HttpResult
     */
    public HttpResult doPost(String url, Map<String, Object> map) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);

        // 判断map不为空
        if (map != null) {
            // 声明存放参数的List集合
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // 遍历map,设置参数到list中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }

            // 创建form表单对象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

            // 把表单对象设置到httpPost中
            httpPost.setEntity(formEntity);
        }

        // 使用HttpClient发起请求,返回response
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
        } catch (IOException e) {
            HttpResult httpResult = new HttpResult();
            httpResult.setCode(404);
            httpResult.setBody("请求失败");
            return httpResult;
        }

        // 解析response封装返回对象httpResult
        HttpResult httpResult = new HttpResult();
        // 解析数据封装HttpResult
        if (response.getEntity() != null) {
            //httpResult = new HttpResult(response.getStatusLine().getStatusCode(),EntityUtils.toString(response.getEntity(),"UTF-8"));
            httpResult.setCode(response.getStatusLine().getStatusCode());
            httpResult.setBody(EntityUtils.toString(response.getEntity(),"UTF-8"));

        } else {
            //httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
            httpResult.setCode(response.getStatusLine().getStatusCode());
            //httpResult.setBody("");
        }

        // 返回结果
        return httpResult;
    }

    /* *
     * Put请求
     * @author miaoqixin
     * @date 2018/11/28 18:14
     * @param [url, map]
     * @return com.example.HttpClient.HttpResult
     */
    public HttpResult doPut(String url, Map<String, Object> map) throws Exception {
        // 声明httpPost请求
        HttpPut httpPut = new HttpPut(url);

        // 判断map不为空
        if (map != null) {
            // 声明存放参数的List集合
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // 遍历map,设置参数到list中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }

            // 创建form表单对象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

            // 把表单对象设置到httpPost中
            httpPut.setEntity(formEntity);
        }

        // 使用HttpClient发起请求,返回response
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPut);
        } catch (IOException e) {
            HttpResult httpResult = new HttpResult();
            httpResult.setCode(404);
            httpResult.setBody("请求失败");
            return httpResult;
        }

        // 解析response封装返回对象httpResult
        HttpResult httpResult = new HttpResult();
        // 解析数据封装HttpResult
        if (response.getEntity() != null) {
            //httpResult = new HttpResult(response.getStatusLine().getStatusCode(),EntityUtils.toString(response.getEntity(),"UTF-8"));
            httpResult.setCode(response.getStatusLine().getStatusCode());
            httpResult.setBody(EntityUtils.toString(response.getEntity(),"UTF-8"));

        } else {
            //httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
            httpResult.setCode(response.getStatusLine().getStatusCode());
            //httpResult.setBody("");
        }

        // 返回结果
        return httpResult;
    }

    /* *
     *  Delete请求
     * @author miaoqixin
     * @date 2018/11/28 18:20
     * @param [url, map]
     * @return com.example.HttpClient.HttpResult
     */
    public HttpResult doDelete(String url, Map<String, Object> map) throws Exception {

        // 声明URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);

        // 判断参数map是否为非空
        if (map != null) {
            // 遍历参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 设置参数
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 2 创建httpGet对象,相当于设置url请求地址
        HttpDelete httpDelete = new HttpDelete(uriBuilder.build());

        // 3 使用HttpClient执行httpGet,相当于按回车,发起请求
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpDelete);
        } catch (IOException e) {
            HttpResult httpResult = new HttpResult();
            httpResult.setCode(404);
            httpResult.setBody("请求失败");
            return httpResult;

        }

        // 4 解析结果,封装返回对象httpResult,相当于显示相应的结果
        // 状态码
        // response.getStatusLine().getStatusCode();
        // 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
        // EntityUtils.toString(response.getEntity(), "UTF-8");
        HttpResult httpResult = new HttpResult();
        // 解析数据封装HttpResult
        if (response.getEntity() != null) {
            //httpResult = new HttpResult(response.getStatusLine().getStatusCode(),EntityUtils.toString(response.getEntity(),"UTF-8"));
            httpResult.setCode(response.getStatusLine().getStatusCode());
            httpResult.setBody(EntityUtils.toString(response.getEntity(),"UTF-8"));

        } else {
            //httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
            httpResult.setCode(response.getStatusLine().getStatusCode());
            //httpResult.setBody("");
        }
        // 返回
        return httpResult;
    }
}

创建HttpClient调用接口的返回实体

package com.example.HttpClient;
import lombok.Data;
import java.io.Serializable;
/**
 * @program: webservice_demo
 * @description: HttpClient返回对象
 * @author: miaoqixin
 * @create: 2018-11-28 16:54
 **/
@Data
public class HttpResult implements Serializable {

    // 响应的状态码
    private int code;

    // 响应的响应体
    private String body;

}

然后用我们通过junit来测试一下接口

package com.example.HttpClient;

import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: webservice_demo
 * @description: 调用测试
 * @author: miaoqixin
 * @create: 2018-11-28 17:21
 **/

public class APIServiceTest {

    private HttpClientUtil apiService;

    @Before
    public void init() {
        this.apiService = new HttpClientUtil();
    }


    // 查询
    @Test
    public void testQueryItemById() throws Exception {
        // http://manager.aaaaaa.com/rest/item/interface/{id}
        String url = "https://www.apiopen.top/weatherApi";
        Map<String, Object> map = new HashMap<>();
        //map.put("id",22222);
        //map.put("name",33333);
        HttpResult httpResult = apiService.doGet(url,map);
        System.out.println(httpResult.getCode());
        System.out.println(httpResult.getBody());
        
    }

    // 新增
    @Test
    public void testSaveItem() throws Exception {
        // http://manager.aaaaaa.com/rest/item/interface/{id}
        String url = "https://www.i12368.com/preservation/auth/checkUsera";
        Map<String, Object> map = new HashMap<String, Object>();
        // title=测试RESTful风格的接口&price=1000&num=1&cid=888&status=1
        map.put("userId", 12343474);
        HttpResult httpResult = apiService.doPost(url, map);
        System.out.println(httpResult.getCode());
        System.out.println(httpResult.getBody());

    }

    // 修改
    @Test
    public void testUpdateItem() throws Exception {
        // http://manager.aaaaaa.com/rest/item/interface/{id}
        String url = "http://manager.aaaaaa.com/rest/item/interface";
        Map<String, Object> map = new HashMap<String, Object>();
        // title=测试RESTful风格的接口&price=1000&num=1&cid=888&status=1
        map.put("title", "测试APIService调用修改接口");
        map.put("id", "44");
        HttpResult httpResult = apiService.doPut(url, map);
        System.out.println(httpResult.getCode());
        System.out.println(httpResult.getBody());
    }


    // 删除
    @Test
    public void testDeleteItemById() throws Exception {
        // http://manager.aaaaaa.com/rest/item/interface/{id}
        String url = "http://manager.aaaaaa.com/rest/item/interface/44";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", "44");
        HttpResult httpResult = apiService.doDelete(url, map);
        System.out.println(httpResult.getCode());
        System.out.println(httpResult.getBody());
    }


}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Java/Android 相关文章推荐
springboot如何初始化执行sql语句
Jun 22 Java/Android
spring项目中切面及AOP的使用方法
Jun 26 Java/Android
Java使用httpRequest+Jsoup爬取红蓝球号码
Jul 02 Java/Android
Java中的随机数Random
Mar 17 Java/Android
SpringBoot中获取profile的方法详解
Apr 08 Java/Android
Flutter Navigator 实现路由传递参数
Apr 22 Java/Android
Android开发 使用文件储存的方式保存QQ密码
Apr 24 Java/Android
Spring Data JPA框架自定义Repository接口
Apr 28 Java/Android
Java中Dijkstra(迪杰斯特拉)算法
May 20 Java/Android
Android开发手册Chip监听及ChipGroup监听
Jun 10 Java/Android
Android基础入门之dataBinding的简单使用教程
Jun 21 Java/Android
SpringBoot项目部署到阿里云服务器的实现步骤
Jun 28 Java/Android
Java Spring读取和存储详细操作
Aug 05 #Java/Android
AndroidStudio图片压缩工具ImgCompressPlugin使用实例
Aug 05 #Java/Android
Java代码规范与质量检测插件SonarLint的使用
Aug 05 #Java/Android
Spring boot admin 服务监控利器详解
Aug 05 #Java/Android
volatile保证可见性及重排序方法
Aug 05 #Java/Android
app场景下uniapp的扫码记录
Jul 23 #Java/Android
IDEA中sout快捷键无效问题的解决方法
Jul 23 #Java/Android
You might like
强烈推荐:php.ini中文版(1)
2006/10/09 PHP
中国站长站 For Dede4.0 采集规则
2007/05/27 PHP
解析php安全性问题中的:Null 字符问题
2013/06/21 PHP
10个php函数实用却不常见
2015/10/13 PHP
PHP数据库操作四:mongodb用法分析
2017/08/16 PHP
JavaScript模拟可展开、拖动与关闭的聊天窗口实例
2015/05/12 Javascript
基于JS实现新闻列表无缝向上滚动实例代码
2016/01/22 Javascript
jQuery使用经验小技巧(推荐)
2016/05/31 Javascript
JS中mouseover和mouseout多次触发问题如何解决
2016/06/06 Javascript
微信小程序 wx:key详细介绍
2016/10/28 Javascript
javascript阻止事件冒泡和浏览器的默认行为
2017/01/21 Javascript
js实现tab切换效果
2017/02/16 Javascript
分享vue里swiper的一些坑
2018/08/30 Javascript
Vue-Quill-Editor富文本编辑器的使用教程
2018/09/21 Javascript
基于axios 解决跨域cookie丢失的问题
2018/09/26 Javascript
JS+HTML5 canvas绘制验证码示例
2018/12/05 Javascript
Python实现获取网站PR及百度权重
2015/01/21 Python
Python实现数通设备端口使用情况监控实例
2015/07/15 Python
Python学习小技巧之列表项的拼接
2017/05/20 Python
python通过getopt模块如何获取执行的命令参数详解
2017/12/29 Python
Python爬虫_城市公交、地铁站点和线路数据采集实例
2018/01/10 Python
详解如何在Apache中运行Python WSGI应用
2019/01/02 Python
python三引号输出方法
2019/02/27 Python
python实现最大优先队列
2019/08/29 Python
python将字符串转变成dict格式的实现
2019/11/18 Python
python-docx文件定位读取过程(尝试替换)
2020/02/13 Python
python向企业微信发送文字和图片消息的示例
2020/09/28 Python
使用HTML5拍照示例代码
2013/08/06 HTML / CSS
台湾乐天市场:日本No.1的网路购物网站
2017/03/22 全球购物
wedgwood加拿大官网:1759年成立的英国国宝级陶瓷餐具品牌
2018/07/17 全球购物
亚洲在线旅行门户网站:Expedia.com.hk(智游网)
2020/04/14 全球购物
公司管理建议书范文
2014/03/12 职场文书
网络编辑岗位职责
2014/03/18 职场文书
电子信息工程专业自荐书
2014/06/24 职场文书
2014年9.18纪念日演讲稿
2014/09/14 职场文书
Java spring单点登录系统
2021/09/04 Java/Android