热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

HttpClient入门(1)发送请求,处理响应及响应重复读取

HttpClient是Apache旗下的项目,是一个负责创建和维护HTTP和相关协议的工具集。以下分析使用版本为:httpclient-4.5.3.ja

HttpClient是Apache旗下的项目,是一个负责创建和维护HTTP和相关协议的工具集。

以下分析使用版本为: httpclient-4.5.3.jar, httpcore-4.4.6.jar, jdk1.8.0_131 所有示例代码均经过运行测试

发送请求

httpclient最重要的功能就是发送http请求,下面介绍如何执行一个get请求:

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet get = new HttpGet("http://www.jianshu.com/u/8a3115bb299c");
try(CloseableHttpResponse response = httpclient.execute(get)) { HttpEntity entity = response.getEntity();System.out.println(EntityUtils.toString(entity, "UTF-8"));
} catch (Exception e) {e.printStackTrace();
}

httpclient支持Http/1.1规范中定义的所有方法:GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,对应的类是:HttpGet,HttpHead,HttpPost,HttpPut,HttpDelete,HttpTrace,HttpOptions。

请求URI

URI(统一资源标识符),用于标识应用请求的资源,通常由协议版本,主机名,端口(可选),资源路径,参数名(可选),参数值(可选)组成。 请求时,可以通过拼接字符串的形式访问:

HttpGet get = new HttpGet("http://www.jianshu.com/p/7021031d6e49?utm_medium=index-banner&utm_source=desktop");

httpclient也提供了URIBuilder这个类简化请求URI的创建和修改。

URI uri = new URIBuilder().setScheme("http").setHost("www.jianshu.com").setPath("/p/7021031d6e49").setParameter("utm_medium", "index-banner").setParameter("utm_source", "desktop").build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());

输出

http://www.jianshu.com/p/7021031d6e49?utm_medium=index-banner&utm_source=desktop

http请求是客户端发给服务端的一个消息,消息的第一行包括了请求方法,URI以及使用的协议版本。

HttpGet get = new HttpGet("http://www.jianshu.com/u/8a3115bb299c");
RequestLine requestLine = get.getRequestLine();
System.out.println(requestLine.getMethod());
System.out.println(requestLine.getUri());
System.out.println(requestLine.getProtocolVersion());
System.out.println(requestLine);

输出

GET
http://www.jianshu.com/u/8a3115bb299c
HTTP/1.1
GET http://www.jianshu.com/u/8a3115bb299c HTTP/1.1

处理响应

服务端接收并处理请求后,会返回消息给到客户端,该消息的第一行包括协议版本,状态码以及描述文字。

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet get = new HttpGet("http://www.jianshu.com/u/8a3115bb299c");
try(CloseableHttpResponse response = httpclient.execute(get)) { System.out.println(response.getStatusLine());System.out.println(response.getProtocolVersion());System.out.println(response.getStatusLine().getStatusCode());System.out.println(response.getStatusLine().getReasonPhrase());System.out.println(response.getStatusLine().toString());
} catch (Exception e) {e.printStackTrace();
}

输出

HTTP/1.1 200 OK
HTTP/1.1
200
OK
HTTP/1.1 200 OK

服务端返回的响应被封装在HttpEntity,通过HttpEntity可以获取请求响应的一些元信息,比如Content-Type,Content-Length以及Content-Encoding,元信息需由服务端提供,否则将是空值。

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet get = new HttpGet("http://www.jianshu.com/u/8a3115bb299c");
try(CloseableHttpResponse response = httpclient.execute(get)) { HttpEntity entity = response.getEntity();System.out.println(entity.getContentType());System.out.println(entity.getContentLength());System.out.println(entity.getContentEncoding());
} catch (Exception e) {e.printStackTrace();
}

输出

Content-Type: text/html; charset=utf-8
-1
null

HttpEntity提供了多种方法来读取正文,官方文档推荐使用以下方法进行读取:HttpEntity.getContent()HttpEntity.writeTo(outputStream)

HttpEntity.getContent()方式

CloseableHttpClient httpclient = null;
CloseableHttpResponse response = null;
BufferedReader reader = null;
try {httpclient = HttpClients.createDefault();HttpGet get = new HttpGet("http://www.jianshu.com/u/8a3115bb299c");response = httpclient.execute(get);HttpEntity entity = response.getEntity();reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));String str = "";StringBuilder sb = new StringBuilder(); while ((str = reader.readLine()) != null) { sb.append(str).append("\n"); }System.out.println(sb);
} catch (Exception e) {e.printStackTrace();
} finally {CommonUtils.closeReader(reader);CommonUtils.closeResponse(response);CommonUtils.closeHttpClient(httpclient);
}

CommonUtils

public void closeReader(BufferedReader reader) {try {if (reader != null) {reader.close();}} catch (Exception e) {e.printStackTrace();}
}public void closeResponse(CloseableHttpResponse response) {try {if (response != null) {response.close();}} catch (Exception e) {e.printStackTrace();}
}public void closeHttpClient(CloseableHttpClient httpclient) {try {if (httpclient != null) {httpclient.close();}} catch (Exception e) {e.printStackTrace();}
}

HttpEntity.writeTo方式

CloseableHttpClient httpclient = null;
CloseableHttpResponse response = null;
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
try {httpclient = HttpClients.createDefault();HttpGet get = new HttpGet("http://www.jianshu.com/u/8a3115bb299c");response = httpclient.execute(get);HttpEntity entity = response.getEntity();entity.writeTo(outstream);System.out.println(outstream.toString("UTF-8"));
} catch (Exception e) {e.printStackTrace();
} finally {CommonUtils.closeOutputStream(outstream);CommonUtils.closeResponse(response);CommonUtils.closeHttpClient(httpclient);
}

CommonUtils

public void closeOutputStream(ByteArrayOutputStream outstream) {try {if (outstream != null) {outstream.close();}} catch (Exception e) {e.printStackTrace();}
}

为了确保资源的正确释放,采用上述两种方式读取正文时,都需对流进行关闭。除此之外,HttpClient还提供了EntityUtils工具类,方便对正文的读取操作,不过官方文档中建议,只有当响应实体来自受信任的HTTP服务器,并且已知其长度有限,才可以采用这种方法。

EntityUtils.toString方式

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet get = new HttpGet("http://www.jianshu.com/u/8a3115bb299c");
try(CloseableHttpResponse response = httpclient.execute(get)) { HttpEntity entity = response.getEntity();System.out.println(EntityUtils.toString(entity, "UTF-8"));
} catch (Exception e) {e.printStackTrace();
} finally {CommonUtils.closeHttpClient(httpclient);
}

EntityUtils.toString内部会对HttpEntity中的输入流进行关闭。 以上三种读取方式,当CloseableHttpClient的实例不再使用时,都需调用close方法进行关闭。

通过BufferedHttpEntity实现响应多次读取

对于流类型的HttpEntity而言,是不可重复读取的,若想多次读取,则需要在某个地方将HttpEntity缓存起来,最简单的方式,可以使用HttpClient提供的BufferedHttpEntity类来实现。

HttpEntity.getContent()+BufferedHttpEntity实现多次读取

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet get = new HttpGet("http://www.jianshu.com/u/8a3115bb299c");
try(CloseableHttpResponse response = httpclient.execute(get)) {HttpEntity entity = response.getEntity();BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(entity);System.out.println(getEntityContent(bufferedEntity));System.out.println(getEntityContent(bufferedEntity));
} catch (Exception e) {e.printStackTrace();
} finally {CommonUtils.closeHttpClient(httpclient);
}

public String getEntityContent(HttpEntity entity) {try(BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"))) {String str = "";StringBuilder sb = new StringBuilder(); while ((str = reader.readLine()) != null) { sb.append(str).append("\n"); }return sb.toString();} catch (Exception e) {e.printStackTrace();return "";}
}

HttpEntity.writeTo+BufferedHttpEntity实现多次读取

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet get = new HttpGet("http://www.jianshu.com/u/8a3115bb299c");
try(CloseableHttpResponse response = httpclient.execute(get)) {HttpEntity entity = response.getEntity();BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(entity);System.out.println(getContentByWriteTo(bufferedEntity));System.out.println(getContentByWriteTo(bufferedEntity));
} catch (Exception e) {e.printStackTrace();
} finally {CommonUtils.closeHttpClient(httpclient);
}

public String getContentByWriteTo(HttpEntity entity) {try(ByteArrayOutputStream outstream = new ByteArrayOutputStream()) {entity.writeTo(outstream);return outstream.toString("UTF-8");} catch (Exception e) {e.printStackTrace();return "";}
}

EntityUtils.toString+BufferedHttpEntity实现多次读取

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet get = new HttpGet("http://www.jianshu.com/u/8a3115bb299c");
try(CloseableHttpResponse response = httpclient.execute(get)) { HttpEntity entity = response.getEntity();BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(entity);System.out.println(EntityUtils.toString(bufferedEntity, "UTF-8"));System.out.println(EntityUtils.toString(bufferedEntity, "UTF-8"));
} catch (Exception e) {e.printStackTrace();
} finally {CommonUtils.closeHttpClient(httpclient);
}

至此,通过HttpClient,简单实现了http get请求的发送和响应处理。




推荐阅读
  • 本文介绍了如何使用Python爬取妙笔阁小说网仙侠系列中所有小说的信息,并将其保存为TXT和CSV格式。主要内容包括如何构造请求头以避免被网站封禁,以及如何利用XPath解析HTML并提取所需信息。 ... [详细]
  • HTTP(HyperTextTransferProtocol)是超文本传输协议的缩写,它用于传送www方式的数据。HTTP协议采用了请求响应模型。客服端向服务器发送一 ... [详细]
  • 解决Only fullscreen opaque activities can request orientation错误的方法
    本文介绍了在使用PictureSelectorLight第三方框架时遇到的Only fullscreen opaque activities can request orientation错误,并提供了一种有效的解决方案。 ... [详细]
  • 如何将TS文件转换为M3U8直播流:HLS与M3U8格式详解
    在视频传输领域,MP4虽然常见,但在直播场景中直接使用MP4格式存在诸多问题。例如,MP4文件的头部信息(如ftyp、moov)较大,导致初始加载时间较长,影响用户体验。相比之下,HLS(HTTP Live Streaming)协议及其M3U8格式更具优势。HLS通过将视频切分成多个小片段,并生成一个M3U8播放列表文件,实现低延迟和高稳定性。本文详细介绍了如何将TS文件转换为M3U8直播流,包括技术原理和具体操作步骤,帮助读者更好地理解和应用这一技术。 ... [详细]
  • Cookie学习小结
    Cookie学习小结 ... [详细]
  • python模块之正则
    re模块可以读懂你写的正则表达式根据你写的表达式去执行任务用re去操作正则正则表达式使用一些规则来检测一些字符串是否符合个人要求,从一段字符串中找到符合要求的内容。在 ... [详细]
  • 一、Tomcat安装后本身提供了一个server,端口配置默认是8080,对应目录为:..\Tomcat8.0\webapps二、Tomcat8.0配置多个端口,其实也就是给T ... [详细]
  • 一个建表一个执行crud操作建表代码importandroid.content.Context;importandroid.database.sqlite.SQLiteDat ... [详细]
  • Spring Data JdbcTemplate 入门指南
    本文将介绍如何使用 Spring JdbcTemplate 进行数据库操作,包括查询和插入数据。我们将通过一个学生表的示例来演示具体步骤。 ... [详细]
  • 我有一个从C项目编译的.o文件,该文件引用了名为init_static_pool ... [详细]
  • 本文详细介绍了如何在 Linux 系统上安装 JDK 1.8、MySQL 和 Redis,并提供了相应的环境配置和验证步骤。 ... [详细]
  • 使用ArcGIS for Java和Flex浏览自定义ArcGIS Server 9.3地图
    本文介绍了如何在Flex应用程序中实现浏览自定义ArcGIS Server 9.3发布的地图。这是一个基本的入门示例,适用于初学者。 ... [详细]
  • 利用python爬取豆瓣电影Top250的相关信息,包括电影详情链接,图片链接,影片中文名,影片外国名,评分,评价数,概况,导演,主演,年份,地区,类别这12项内容,然后将爬取的信息写入Exce ... [详细]
  • 本文介绍如何在 Android 中自定义加载对话框 CustomProgressDialog,包括自定义 View 类和 XML 布局文件的详细步骤。 ... [详细]
  • 网站访问全流程解析
    本文详细介绍了从用户在浏览器中输入一个域名(如www.yy.com)到页面完全展示的整个过程,包括DNS解析、TCP连接、请求响应等多个步骤。 ... [详细]
author-avatar
天雨
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有