HttpClient 的GET(带参数)POST请求方式,工具类方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient 的GET(带参数)POST请求方式,工具类方法相关的知识,希望对你有一定的参考价值。

/**
 * 连接/断开操作 post方式
 * @param url
 * @param json
 */
private boolean connOrDisconnOperator(String url,String json){
    CloseableHttpClient client = null;
    CloseableHttpResponse response = null;
    boolean flag = false;
    try{
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(50000)
                .setSocketTimeout(50000)
                .setConnectionRequestTimeout(120000).build();
        httpPost.setConfig(requestConfig);
        List<BasicNameValuePair> list = Lists.newArrayListWithExpectedSize(1);
        list.add(new BasicNameValuePair("json",json));
        httpPost.setEntity(new UrlEncodedFormEntity(list));
        client = HttpClients.createDefault();
        response = client.execute(httpPost);
        if(response.getStatusLine().getStatusCode() == 200){
            InputStream is = response.getEntity().getContent();
            Map<String,Object> m = new ObjectMapper().readValue(StringUtil.getString(is),Map.class);
            String strState = m.get("state").toString();
            if("SUCCESS".equals(strState)){
                flag = true;
            }
        }else{
            log.error(this.getClass(), "connOrDisconnOperator method fail:" + response.getStatusLine().getStatusCode());
        }
    }catch (Exception ex){
        log.error(this.getClass(), "connOrDisconnOperator method error",ex);
    }finally {
        if(response != null){
            try {
                response.close();
            } catch (IOException ex) {
                log.error(this.getClass(), "close response method error", ex);
            }
        }
        if(client != null){
            try {
                client.close();
            } catch (IOException ex) {
                log.error(this.getClass(), "close client method", ex);
            }
        }
    }
    return flag;
}
// get方式
public Optional<Map<String,Object>> connOrDisconnOperator(String atisAirPortCode, String url) {
    CloseableHttpClient client = null;
    CloseableHttpResponse response = null;
    try{
        HttpGet httpGet = new HttpGet(url + "?airportCode=" +atisAirPortCode);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(120000).build();
        httpGet.setConfig(requestConfig);
        client = HttpClients.createDefault();
        response = client.execute(httpGet);
        if(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 500){
            Map<String,Object> map = Maps.newHashMapWithExpectedSize(4);
            InputStream is = response.getEntity().getContent();
            JsonNode jn = new ObjectMapper().readTree(StringUtil.getString(is));

            // 解析返回结果
            String result = jn.get("state").asText();
            if (result.equals("SUCCESS")) {
                System.out.println("-----------------------------成功");
            } else {
                System.out.println("-----------------------------失败");
            }
            return Optional.of(map);
        }else{
            return Optional.absent();
        }
    }catch (Exception ex) {
        log.error(this.getClass(), "getOSInfo() error", ex);
        return Optional.absent();
    }finally {
        if(response != null){
            try {
                response.close();
            } catch (IOException ex) {
                log.error(this.getClass(), "close IO error", ex);
            }
        }
        if(client != null){
            try {
                client.close();
            } catch (IOException ex) {
                log.error(this.getClass(),"close IO error",ex);
            }
        }
    }
}

以上是关于HttpClient 的GET(带参数)POST请求方式,工具类方法的主要内容,如果未能解决你的问题,请参考以下文章

排名第 1 的爬虫框架,到底有多牛逼?

后台发送请求,HttpClient的post,get各种请求,带header的请求

HttpClient模拟get,post请求并发送请求参数(json等)

java网络爬虫

Android攻城狮httpClient post/get传递参数

HttpClient POST/SET方法