博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HttpClient——概述(一)
阅读量:6787 次
发布时间:2019-06-26

本文共 4011 字,大约阅读时间需要 13 分钟。

一、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.1200OKHTTP/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);}

未完待续....

转载地址:http://bdkgo.baihongyu.com/

你可能感兴趣的文章
ntp redhat
查看>>
sum(case when status=1 then 1 else 0 end) 的意思
查看>>
Win7硬盘安装方法
查看>>
python - 列表
查看>>
UIVisualEffectView用法
查看>>
springmvc+mybatis整合cms+UC浏览器文章功能
查看>>
docker安装(centos6.5_x86_64)
查看>>
mysql悲观锁与乐观锁
查看>>
ubuntu下python2-python3版共存,创建django项目出现的问题
查看>>
2018.4.3三周第二次课
查看>>
eclipse_jee版本提供了从数据库直接生成实体类的工具!
查看>>
Error: Can't set headers after they are sent
查看>>
本地用户模式、虚拟用户模式使用
查看>>
任正非接班人亮相:原来他要的是这种类型!
查看>>
valgrind 运行出错
查看>>
ubuntu日常使用心得(随时更新中。。。)
查看>>
Java 多线程回顾
查看>>
二、nginx服务器基础配置命令
查看>>
TEMP表空间之Ogg复制进程占用
查看>>
java中的构造函数总结
查看>>