HttpClient远程访问api(包含get、post表单和json请求)

本文分享的内容是通过HttpClient远程访问接口,内容有现在普遍使用的body请求体存放json参数访问调用接口 ,分享给大家:



public class HttpClientUtil {
    private final static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
    private static final String CHARACTER_ENCODING = "UTF-8";
    private static CloseableHttpClient httpClient = null;

    static {
       //初始化httpClient
       httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
    }

    /**
     * get不带参
     *
     * @param url 请求路径
     */
    public static String get(String url) throws IOException{
        if (StringUtils.isBlank(url)) {
            return null;
        }
        logger.warn("请求url======"+url);
        //设置请求参数
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        return parse(response);
    }

    /**
     * post json
     *
     * @param url 请求路径
     * @param map 请求参数
     * @return
     */
    public static String postForm(Map<String, String> map, String url) throws IOException{
        if (StringUtils.isBlank(url) || map == null) {
            return null;
        }
        logger.warn("请求url======"+url);
        //设置请求参数
        HttpPost httpPost = new HttpPost(url);
        //构建消息实体 map转json
        StringEntity entity = new StringEntity(JSONQbject.toJSONString(map));
        entity.setContentEncoding(CHARACTER_ENCODING);
        entity.setContentType("application/json");
        //发送json格式的数据请求
        httpPost.setEntity(entity);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        return parse(response);
    }

  

    /**
     * 解析结果集
     *
     * @param response
     * @return
     * @throws IOException
     */
    protected static String parse(CloseableHttpResponse response) throws IOException {
        String result = null;
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            result = "";
            if (statusCode != 200) {
                return result;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, CHARACTER_ENCODING);
                //释放底层持有的httpEntity资源
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            logger.error("parse error{}", ExceptionUtils.getStackFrames(e));
        } finally {
            response.close();
        }
        return result;
    }
}

 以上是关于Httpclient远程访问接口的内容,希望给大家带来帮助。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值