HttpClient使用详解

HttpClient的主要功能:

  • 实现了所有 HTTP 的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)
  • 支持 HTTPS 协议
  • 支持代理服务器(Nginx等)等
  • 支持自动(跳转)转向
  • 等等

 

引入依赖

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>

 

使用详解

1. get方法

public class GetUtils {

//无参方式
public void get(String url) {
getWithParams(url, new HashMap<>());
}

//有参方式
public void getWithParams(String url, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = null;
try {
// 创建Get请求
url = joinParam(url, params);
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(2000) //服务器响应超时时间
.setConnectTimeout(2000) //连接服务器超时时间
.build();
httpGet.setConfig(requestConfig);
// 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

private static String joinParam(String url, Map<String, Object> params) {
if (params == null || params.size() == 0) {
return url;
}

StringBuilder urlBuilder = new StringBuilder(url);
urlBuilder.append("?");

int counter = 0;
for (Map.Entry<String,Object> entry : params.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (key == null) {
continue;
}

if (counter == 0) {
urlBuilder.append(key).append("=").append(value);
} else {
urlBuilder.append("&").append(key).append("=").append(value);
}
counter++;
}

return urlBuilder.toString();
}

}

 

2. post方法

post请求有两种方式传参,一种是普通参数,一种是对象参数。普通参数传参方式和上面的get请求相同,对象参数需要使用setEntity()方法设置,同时需要指定请求的content-type

以下两段代码均为对象方式传参

2.1 content-type为:application/x-www-form-urlencoded

public class PostUtils {

    public void post(String url) {
        postWithParams(url, new HashMap<>());
    }

    public void postWithParams(String url, Map<String, String> params) {
        List<NameValuePair> pairs = generatePairs(params);

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(2000) //服务器响应超时时间
                    .setConnectTimeout(2000) //连接服务器超时时间
                    .build();
            httpPost.setConfig(requestConfig);

            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, "utf-8");
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            // 由客户端执行(发送)请求
            response = httpClient.execute(httpPost);
            System.out.println("响应状态为:" + response.getStatusLine());
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private List<NameValuePair> generatePairs(Map<String, String> params) {
        if (params == null || params.size() == 0) {
            return Collections.emptyList();
        }

        List<NameValuePair> pairs = new ArrayList<>();
        for (Map.Entry<String,String> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (key == null) {
                continue;
            }

            pairs.add(new BasicNameValuePair(key, value));
        }

        return pairs;
    }

}

 

2.1 content-type为:application/json

public void postWithParams(String url, UserEntity userEntity) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(2000) //服务器响应超时时间
                    .setConnectTimeout(2000) //连接服务器超时时间
                    .build();
            httpPost.setConfig(requestConfig);

            StringEntity entity = new StringEntity(JSON.toJSONString(userEntity), "utf-8");//也可以直接使用JSONObject
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/json;charset=utf8");
            // 由客户端执行(发送)请求
            response = httpClient.execute(httpPost);
            System.out.println("响应状态为:" + response.getStatusLine());
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

其他

提示:网上有很多开源的http工具类,Github上Star非常多的一个HttpClient的工具类是httpclientutil,该工具类的编写者封装了很多功能在里面,如果

           不是有什么特殊的需求的话,完全可以直接使用该工具类。使用方式很简单,可详见https://github.com/Arronlong/httpclientutil

 

posted @ 2019-07-11 18:21  桥er桑  阅读(12640)  评论(0编辑  收藏  举报