HttpClient的简单样例展示

写在前面

其实本身 jdk 自带的 net 库是可以实现 http 接口请求的,但是实现起来过于繁琐,httpclient 依赖很好的解决了这个问题,它本身是 Apache Jakarta Common 下的子项目。

配合 httpclient 使用的还有 gson 和 fastjson,二者都是可以做对象转 json 和 json 转对象的工作,gson 是谷歌研发的依赖,性能虽然比不过 fastjson 但是效果上是绝对没有问题的,fastjson 是阿里巴巴的开源的依赖,采用了新的算法,性能是可以说是最强的存在,但是对于复杂类型对象转 json 可能存在问题。所以一般在做后端开发的时候,很多人喜欢使用 gson 将对象转 json,使用 fastjson 将 json 转对象

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.9</version>
</dependency>

实现 GET 请求

http 的 get 请求若是没有参数,下面参数部分的代码可以去掉,对于传纯字符的参数,建议是有用URLEncoder.encode("name=liming", "utf-8")这种方式

// http 客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();

// get 请求参数
StringBuffer params = new StringBuffer();
try {
    params.append(URLEncoder.encode("name=liming", "utf-8"))
            .append("&")
            .append("age=20");
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

// get 请求
HttpGet httpGet = new HttpGet("这里写 http 地址" + "?" + params);

// get 请求设置响应模型
RequestConfig requestConfig = RequestConfig.custom()
        .setConnectTimeout(5000)
        .setConnectionRequestTimeout(5000)
        .setSocketTimeout(5000)
        .setRedirectsEnabled(true)
        .build();
httpGet.setConfig(requestConfig);

// 客户端发送 get 请求并获取 http 响应
CloseableHttpResponse httpResponse = null;
try {
    httpResponse = httpClient.execute(httpGet);
} catch (IOException e) {
    e.printStackTrace();
}

// 获取响应状态
System.out.println("响应状态:" + httpResponse.getStatusLine());

// 获取响应实体
HttpEntity httpEntity = httpResponse.getEntity();
System.out.println("响应内容长度:" + httpEntity.getContentLength());
try {
    System.out.println("响应内容:" + EntityUtils.toString(httpEntity));
} catch (IOException e) {
    e.printStackTrace();
}

实现 POST 请求

下方我借助了 gson 将对象转成 json 字符串

gson 需要引入依赖

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>
// http 客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();

// post 请求
HttpPost httpPost = new HttpPost("这里写 http 地址");

// post 请求设置请求头
httpPost.setHeader("Content-Type", "application/json;charset=utf8");

// post 请求设置参数
User user = new User();
user.setName("liming");
user.setAge(20);
Gson gson = new Gson();
String jsonStr = gson.toJson(user);
StringEntity stringEntity = new StringEntity(jsonStr, "UTF-8");
httpPost.setEntity(stringEntity);

// post 请求设置响应模型
RequestConfig requestConfig = RequestConfig.custom()
        .setConnectTimeout(5000)
        .setConnectionRequestTimeout(5000)
        .setSocketTimeout(5000)
        .setRedirectsEnabled(true)
        .build();
httpPost.setConfig(requestConfig);

// 客户端发送 post 请求并获取 http 响应
HttpResponse httpResponse = null;
try {
    httpResponse = httpClient.execute(httpPost);
} catch (IOException e) {
    e.printStackTrace();
}

// 获取相应状态码
System.out.println("响应状态:" + httpResponse.getStatusLine());

// 获取响应实体
HttpEntity httpEntity = httpResponse.getEntity();
System.out.println("响应内容长度:" + httpEntity.getContentLength());
try {
    System.out.println("响应内容:" + EntityUtils.toString(httpEntity));
} catch (IOException e) {
    e.printStackTrace();
}

猜你喜欢

转载自blog.csdn.net/abcnull/article/details/107596974