HttpClient——概述(一)

简介: httpClient使用简介,以及常用的方法,

一、HttpClient scope

1.Client-side HTTP transport library based on HttpCore
2.Based on classic (blocking) I/O
3.Content agnostic

二、HttpClient能做什么?

1.HttpClient不是浏览器
2.HttpClient只能发送、接收请求,传输数据
3.HttpClient不解析返回数据


支持的请求类型
GET, HEAD, POST, PUT, DELETE, TRACE and OPTIONS.
对应的方法类型
HttpGet,HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, HttpOptions.

三、执行请求的基本代码块


CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
    <...>
} finally {
    response.close();
}



HttpRequestType

四、Http Request URI的组成与HTTP请求

HTTP request URIs consist of a protocol scheme, host name, optional port, resource path, optional query, and optional fragment.

URI uri = new URIBuilder()
        .setScheme("http")
        .setHost("www.google.com")
        .setPath("/search")
        .setParameter("q", "httpclient")
        .setParameter("btnG", "Google Search")
        .setParameter("aq", "f")
        .setParameter("oq", "")
        .build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());

stdout

http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq=


五、HTTP Response(这个是指我们调用接口后需要返回消息体给对方)


HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 
HttpStatus.SC_OK, "OK");

System.out.println(response.getProtocolVersion());
System.out.println(response.getStatusLine().getStatusCode());
System.out.println(response.getStatusLine().getReasonPhrase());
System.out.println(response.getStatusLine().toString());



stdout

HTTP/1.1
200
OK
HTTP/1.1 200 OK


六、设置响应头

读取head的时候有两种方式:
方式一:

HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 
    HttpStatus.SC_OK, "OK");
response.addHeader("Set-Cookie", 
    "c1=a; path=/; domain=localhost");
response.addHeader("Set-Cookie", 
    "c2=b; path=\"/\", c3=c; domain=\"localhost\"");
Header h1 = response.getFirstHeader("Set-Cookie");
System.out.println(h1);
Header h2 = response.getLastHeader("Set-Cookie");
System.out.println(h2);
Header[] hs = response.getHeaders("Set-Cookie");
System.out.println(hs.length);

方式二: 使用HeaderIterator

HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 
    HttpStatus.SC_OK, "OK");
response.addHeader("Set-Cookie", 
    "c1=a; path=/; domain=localhost");
response.addHeader("Set-Cookie", 
    "c2=b; path=\"/\", c3=c; domain=\"localhost\"");

HeaderIterator it = response.headerIterator("Set-Cookie");

while (it.hasNext()) {
    System.out.println(it.next());
}


七、HTTP Entity (HTTP消息实体)

消息体存在于请求体或者响应体中,HttpClient通过内容的源来区分三种消息体:
streamed:
The content is received from a stream, or generated on the fly. Streamed entities are generally not repeatable.
self-contained:
Self-contained entities are generally repeatable, will be mostly used for entity enclosing HTTP requests
wrapping:
The content is obtained from another entity.
补充:The HTTP specification defines two entity enclosing request methods: POST and PUT.


处理流类型消息体时,注意释放资源

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        try {
            // do something useful
        } finally {
            instream.close();
        }
    }
} finally {
    response.close();
}



The difference between closing the content stream and closing the response is that the former will attempt to keep the underlying connection alive by consuming the entity content while the latter immediately shuts down and discards the connection.
译:关闭流消息体和关闭响应的区别是前者通过消费(读取)消息体的内容的方式尝试保持连接的存活,而后者则是立即断开连接。—— (有待于纠正)

在我们使用streaming entities时,我们也可以使用EntityUtils.consume(HttpEntity) 方法来确保消息体的内容全部被读完(or has been fully consumed),并且Stream连接已经关闭。


处理包装类型的资源:(使用背景:在我们想多次使用content的时候我们需要缓存资源)

CloseableHttpResponse response = <...>
HttpEntity entity = response.getEntity();
if (entity != null) {
    entity = new BufferedHttpEntity(entity);
}


未完待续....

目录
相关文章
|
网络协议 Java 应用服务中间件
tomcat配置域名及HTTPS
tomcat配置域名及HTTPS
|
9月前
|
数据管理 测试技术 持续交付
软件测试中的自动化测试策略与最佳实践
在当今快速迭代的软件开发环境中,自动化测试已成为确保软件质量和加速产品上市的关键手段。本文旨在探讨软件测试中的自动化测试策略,包括选择合适的自动化测试工具、构建有效的自动化测试框架以及实施持续集成和持续部署(CI/CD)。通过分析自动化测试的最佳实践,本文为软件开发团队提供了一系列实用的指南,以优化测试流程、提高测试效率并减少人为错误。
235 4
|
11月前
|
存储 SQL 分布式计算
大数据-125 - Flink State 02篇 状态原理和原理剖析:广播状态
大数据-125 - Flink State 02篇 状态原理和原理剖析:广播状态
139 0
|
11月前
|
机器学习/深度学习 数据采集 自然语言处理
如何使用 Word2Vec 模型进行情感分析?
【10月更文挑战第5天】如何使用 Word2Vec 模型进行情感分析?
239 3
|
JavaScript 前端开发 数据可视化
富文本编辑器使用详细介绍
富文本编辑器使用详细介绍
402 0
|
11月前
|
开发工具 iOS开发 MacOS
【Mac_mistake】app不能安装在未命名需要OSv11.13或更高版本
【Mac_mistake】app不能安装在未命名需要OSv11.13或更高版本
666 0
|
负载均衡 Kubernetes 网络协议
如何在集群的负载均衡过程保留请求源IP
本文探讨了在Kubernetes (k8s)集群中如何确保服务获取到请求的源IP。通常,源IP可能会因网络地址转换(NAT)和代理服务器而丢失。为保留源IP,文章建议在代理服务器层添加HTTP头`X-REAL-IP`字段。在K8s中,通过设置`externalTrafficPolicy: Local`可保留源IP,但这会牺牲负载均衡。使用Ingress时,可通过配置Ingress Controller的`use-forwarded-headers`并调整ConfigMap来同时保留源IP和实现负载均衡。文章适用于对网络和K8s感兴趣的读者。
320 3
|
Kubernetes 容器 Perl
[k8s]使用私有harbor镜像源
[k8s]使用私有harbor镜像源
147 0
|
消息中间件 运维 Java
支付系统的心脏:简洁而精妙的状态机设计与核心代码实现
本篇主要讲清楚什么是状态机,简洁的状态机对支付系统的重要性,状态机设计常见误区,以及如何设计出简洁而精妙的状态机,核心的状态机代码实现等。 我前段时间面试一个工作过4年的同学竟然没有听过状态机。假如你没有听过状态机,或者你听过但没有写过,或者你是使用if else 或switch case来写状态机的代码实现,建议花点时间看看,一定会有不一样的收获。
|
存储 安全 数据管理
【专栏】指导在Rocky Linux 8上安装配置Elasticsearch,包括添加仓库等
【4月更文挑战第28天】本文指导在Rocky Linux 8上安装配置Elasticsearch,包括添加仓库,运行`yum install elasticsearch`进行安装,修改配置文件如`cluster.name`和`network.host`,启动服务并验证其正常运行。同时,文章提及了内存、文件描述符设置及安全配置,并列出常见问题及解决方法,帮助用户成功搭建Elasticsearch。
270 1