用Httpclient调用第三方接口的方法

在pom.xml中加入maven依赖jar包:
<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.5.2</version>
</dependency>

/**
 * 调用第三方接口方法.
 * @param url 第三方提供的路径
 * @param params 向第三方发送的数据,大多数情况下给对方发送JSON数据让对方解析
 * @param method 请求方式
 */
public JSONData interfaceUtil(String url,String params,String method,String token) {
    Map<String, Object> resultMap = null;
    String strResult = null;
    try {
        if(FinalUtil.REQUEST_METHOD.REQUEST_METHOD_0.equals(method)){//请求方式是get请求
            try {
                HttpClient client = new DefaultHttpClient();
                HttpGet htttpGet = new HttpGet(url);
                if(StringUtils.isNotEmpty(token)){
                    htttpGet.setHeader("Authorization",token);
                }
                //设置请求的报文头部的编码
                htttpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"));
                //设置期望服务端返回的编码
                htttpGet.setHeader(new BasicHeader("Accept", "application/json;charset=utf-8"));
                HttpResponse response = client.execute(htttpGet);
                String charset = "UTF-8";
                /**请求发送成功,并得到响应**/
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    /**读取服务器返回过来的json字符串数据**/
                    // 使用EntityUtils的toString方法,传递编码,默认编码是ISO-8859-1
                    strResult = EntityUtils.toString(response.getEntity(),charset);
                    resultMap = JSONUtil.convertJsonToMap(strResult);
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }else {//是post、put、delete请求方式之一
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String charSet = "UTF-8";
            if(FinalUtil.REQUEST_METHOD.REQUEST_METHOD_1.equals(method)){//请求方式是post请求
                HttpPost httpPost = new HttpPost(url);// 创建httpPost
                if(StringUtils.isNotEmpty(token)){
                    httpPost.setHeader("Authorization",token);
                }
                httpPost.setHeader("Accept", "application/json;charset=utf-8");
                httpPost.setHeader("Content-Type", "application/json;charset=utf-8");

                if(StringUtils.isNotEmpty(params)){
                    StringEntity entity = new StringEntity(params, charSet);
                    httpPost.setEntity(entity);
                }
                response = httpclient.execute(httpPost);
            }else if(FinalUtil.REQUEST_METHOD.REQUEST_METHOD_2.equals(method)){//请求方式是PUT请求
                HttpPut httpPut = new HttpPut(url);// 创建httpPut
                if(StringUtils.isNotEmpty(token)){
                    httpPut.setHeader("Authorization",token);
                }
                httpPut.setHeader("Accept", "application/json;charset=utf-8");
                httpPut.setHeader("Content-Type", "application/json;charset=utf-8");

                if(StringUtils.isNotEmpty(params)){
                    StringEntity entity = new StringEntity(params, charSet);
                    httpPut.setEntity(entity);
                }
                response = httpclient.execute(httpPut);
            }else if(FinalUtil.REQUEST_METHOD.REQUEST_METHOD_3.equals(method)){//请求方式DELETE请求
                HttpDelete httpDelete = new HttpDelete(url);// 创建httpDelete
                if(StringUtils.isNotEmpty(token)){
                    httpDelete.setHeader("Authorization",token);
                }
                httpDelete.setHeader("Accept", "application/json;charset=utf-8");
                httpDelete.setHeader("Content-Type", "application/json;charset=utf-8");
                response = httpclient.execute(httpDelete);
            }
            try {
                StatusLine status = response.getStatusLine();
                int state = status.getStatusCode();
                if (state == HttpStatus.SC_OK) {
                    HttpEntity responseEntity = response.getEntity();
                    // 使用EntityUtils的toString方法,传递编码,默认编码是ISO-8859-1
                    strResult = EntityUtils.toString(responseEntity,charSet);
                    resultMap = JSONUtil.convertJsonToMap(strResult);
                }else{
                    logger.error("请求返回:"+state+"("+url+")");
                    return new JSONData(false,"接口请求失败!!!");
                }
            }
            finally {
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new JSONData(resultMap);
}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值