51

学习 HttpComponents

 5 years ago
source link: https://www.tuicool.com/articles/yMR3ueu
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Apache HttpComponents 是 Commons HttpClient 在 ASF 下新的项目,创建并维护了 HTTP 相关的底层 Java 组件工具集。

项目包括:

  • HttpComponents Core HttpCore 是用于构建自定义的 HTTP 客户端和服务端的底层 HTTP 传输组件。支持两种 I/O 模型:基于传统 Java I/O 的阻塞 I/O 模型和基于 Java NIO 的事件驱动 I/O 模型。
  • HttpComponents Client HttpClient 是构建在 HttpCore 上 HTTP/1.1 兼容的 HTTP 客户端实现。
  • HttpComponents AsyncClint Async HttpClient 是构建在 HttpCore NIO 和 HttpClient 组件上 HTTP/1.1 兼容的 HTTP 客户端实现。

HttpClient

依赖

编辑 pom.xml 文件,添加依赖:

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

GET

CloseableHttpClient httpClient = HttpClients.createDefault(); // ①

HttpGet request = new HttpGet(url); // ②  
HttpResponse response = httpClient.execute(request); // ③

StatusLine status = response.getStatusLine(); // ④  
if (status.getStatusCode() >= 200 && status.getStatusCode() < 300) {  
    HttpEntity entity = response.getEntity(); // ⑤
} else {
    throw new ClientProtocolException(status.getStatusCode() + " " + status.getReasonPhrase());
}

httpClient.close();

① 创建默认的 HTTP 客户端;

② 根据 URL 创建 HTTP GET 请求;

③ 执行 HTTP GET 请求,并返回响应;

④ 判断响应状态,状态码 [200, 300) 之间,代表正常否则抛出异常;

⑤ 获取响应内容,可以使用工具类 EntityUtils 获取字符串或字节内容。

POST

HTTP POST 提交 JSON 数据:

CloseableHttpClient httpClient = HttpClients.createDefault(); // ①

HttpPost request = new HttpPost(url); // ②  
request.setEntity(new StringEntity(json, "utf-8"));  
HttpResponse response = httpClient.execute(request); // ③

StatusLine status = response.getStatusLine(); // ④  
if (status.getStatusCode() >= 300) {  
    throw new ClientProtocolException(status.getStatusCode() + " " + status.getReasonPhrase());
}

httpClient.close();

① 创建默认的 HTTP 客户端;

② 根据 URL 创建 HTTP POST 请求,并设置 HTTP Body;

③ 执行 HTTP POST 请求,并返回响应;

④ 判断响应状态,状态码 [300, +∞) 抛出异常。

HTTP POST 提交表单数据:

TODO

HTTP POST 上传文件:

TODO


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK