HttpClients使用详情介绍

前提

最近我所负责的项目需要向其他项目调用接口,用到了HttpClients实现请求调用。项目请求大多数分为get、post、put、delete,下面我们就分别介绍所对应HttpClients实现过程。

正文

get(httpGet)请求

我们知道get请求大多数需要参数,并且以?的形势拼接在URL后面,所以需要两个参数(URL和param),当不需要参数时,可以传空。返回值我比较喜欢用Object,无论里面返回JSONObject,或者是String,都可以,下面展示代码:

/**
    * get请求
    * @param url
    * @param param
    * @return
    */
 public static Object doGet(String url, Map<String, String> param) {

        //创建HttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //返回的字符串
        String resultString = "";
        JSONObject jsonObject = new JSONObject();
        CloseableHttpResponse response = null;
        try {
            //创建url
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            //创建get请求
            HttpGet httpGet = new HttpGet(builder.toString());
            // 执行请求
            response = httpclient.execute(httpGet);
            //判断返回值是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            //将字符串转JSONObject(可以获取里面得某个元素),也可以直接返回字符串
            jsonObject = JSONObject.parseObject(resultString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

post(httpPost)请求

对于post请求我们大多需要传一个实体,在controller用@RequestBody接收,此时我们传输的应在Body中,并且格式为Json,在请求中如果设置参数类型,默认application/x-www-form-urlencoded;charset=utf-8,这样接收方会报错(type不匹配),我们需要单独设置参数类型,下面展示代码:

  /**
     * post设置参数json
     * @param url
     * @param param
     * @return
     */
    public static String doPostJson(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            String json = JSONObject.toJSON(param).toString();
            // 设置参数为Json,模拟表单
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            // 把参数赋值给请求
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

delete(httpDelete)请求

对于delete请求我们也需要参数,可能是一个id,可能是一个实体,但是看源码发现delete没有传参数的方法,但是poet可以,对比发现他们的父类不同,所以我想到,重写一个HttpDelete,让他的父类继承自HttpPost的父类。下面展示代码:

/**
 * @ClassName HttpDeleteWithBody
 * @Author 程序员pp
 * @Date 2021/1/11 17:14
 * @Version 1.0
 **/
@NotThreadSafe
class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
    public static final String METHOD_NAME = "DELETE";

    @Override
    public String getMethod() {
        return METHOD_NAME;
    }

    public HttpDeleteWithBody(final String uri) {
        this.setURI(URI.create(uri));
    }

    public HttpDeleteWithBody(final URI uri) {
        this.setURI(uri);
    }

    public HttpDeleteWithBody() {
        super();
    }
}

 /**
     * 调用自己创建的delete
     * @param url
     * @param param
     * @return
     */
    public static String doDelete(String url,Map<String,String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建自己创建的HttpDeleteWithBody请求
            HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
            // 创建请求内容
            String json = JSONObject.toJSON(param).toString();
            // 设置参数为Json,模拟表单
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            // 把参数赋值给请求
            httpDelete.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpDelete);
            if (response.getStatusLine().getStatusCode() == 200) {
            	resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

结束

成功呈概率分布,关键是你能不能坚持到成功开始呈现的那一刻,各位加油呦!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值