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远程访问接口的内容,希望给大家带来帮助。

经验分享 程序员 微信小程序 职场和发展