HttpClient Get Post 使用

HttpClient 4.5.2

//添加请求参数
List<BasicNameValuePair> paramList = new ArrayList<>();
paramList.add(new BasicNameValuePair("a", "1"));
paramList.add(new BasicNameValuePair("b", "2"));

// 设置超时
RequestConfig requestConfig = RequestConfig.custom()
        .setConnectTimeout(5000)
        .setConnectionRequestTimeout(1000)
        .setSocketTimeout(5000)
        .build();

参数和返回都转成utf-8

Get

try(
        CloseableHttpClient client = HttpClients.createDefault();
        ){
    // 转换get参数
    String covertParams = EntityUtils.toString(new UrlEncodedFormEntity(paramList, Consts.UTF_8));
    HttpGet httpGet = new HttpGet(url + "?" + covertParams);
    httpGet.setConfig(requestConfig);
    
    CloseableHttpResponse response = client.execute(httpGet);
    resultJson = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
}catch (IOException e){
    e.printStackTrace();
}

Post

HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
try (
        CloseableHttpClient client = HttpClients.createDefault();
        ){
    httpPost.setEntity(new UrlEncodedFormEntity(paramList, Consts.UTF_8));
    
    CloseableHttpResponse response = client.execute(httpPost);
    resultJson = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
} catch (Exception e) {
    e.printStackTrace();
}

参考:
HttpClient详细使用示例

发布了57 篇原创文章 · 获赞 11 · 访问量 9858

猜你喜欢

转载自blog.csdn.net/qq_36160730/article/details/103574735