转自:
http://www.java265.com/JavaCourse/202204/2935.html
HttpClient是一个java语言编写的包,
我们使用HttpClient可以非常方便的发送Http请求
它使基于Http协议请求内容变得非常简单
HttpClient是Apache Jakarta Common下的子项目 它里面封装了很多使用http协议访问的工具,可用于高效访问http
下文笔者讲述基于HttpClient Utils工具类编写一个get请求的示例分享,如下所示:- 实现思路:
- 1.获取连接
- 2.声明一个HttpGet
- 3.execute获取信息
- 4.getEntity获取返回信息
- 5.关闭连接
复制代码- /**
- * 发送 get请求
- */
- public void get() {
- CloseableHttpClient httpclient = HttpClients.createDefault();
- try {
- // 创建httpget.
- HttpGet httpget = new HttpGet("http://www.java265.com/");
- System.out.println("executing request " + httpget.getURI());
- // 执行get请求.
- CloseableHttpResponse response = httpclient.execute(httpget);
- try {
- // 获取响应实体
- HttpEntity entity = response.getEntity();
- System.out.println("--------------------------------------");
- // 打印响应状态
- System.out.println(response.getStatusLine());
- if (entity != null) {
- // 打印响应内容长度
- System.out.println("Response content length: " + entity.getContentLength());
- // 打印响应内容
- System.out.println("Response content: " + EntityUtils.toString(entity));
- }
- System.out.println("------------------------------------");
- } finally {
- response.close();
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (ParseException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- // 关闭连接,释放资源
- try {
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |