[size=large][b]1:概述[/b][/size]
HttpClient是HttpComponents(简称为hc)项目其中的一部份,访问地址:http://hc.apache.org/
[img]http://dl.iteye.com/upload/attachment/584521/ddaadc93-0ccc-3248-95d2-4a0c5820f9a6.png[/img]
HttpClient是一个代码级的Http客户端工具,可以使用它模拟浏览器向Http服务器发送请求。使用HttpClient还需要HttpCore.后者包括Http请求与Http响应的代码封装。

[img]http://dl.iteye.com/upload/attachment/584523/69c45455-7ccd-3229-b3ea-802549771684.png[/img]

[size=large][b]2:HttpGet[/b][/size]

    public final static void main(String[] args) throws Exception {          HttpClient httpclient = new DefaultHttpClient();          try {              HttpGet httpget = new HttpGet("http://www.apache.org/");              System.out.println("executing request " + httpget.getURI());              HttpResponse response = httpclient.execute(httpget);              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("----------------------------------------");  

            InputStream inSm = entity.getContent();              Scanner inScn = new Scanner(inSm);              while (inScn.hasNextLine()) {                  System.out.println(inScn.nextLine());              }              // Do not feel like reading the response body              // Call abort on the request object  关闭            httpget.abort();          } finally {              // When HttpClient instance is no longer needed,              // shut down the connection manager to ensure              // immediate deallocation of all system resources  关闭            httpclient.getConnectionManager().shutdown();          }      }  

[img]http://dl.iteye.com/upload/attachment/584532/38d19a0e-b98f-3d13-a209-fcff5105bcb7.png[/img]
[b]httpcore:EntityUtils.toString(httpEntity)[/b]

读取response响应内容部分,也可以借助于 httpcore-4.1.2.jar 里面的
String content = EntityUtils.toString(httpEntity);
具体:

       public class Demo1 {  

        /**          * 用 get 方法访问 www.apache.org 并返回内容          *          * @param args          */          public static void main(String[] args) {              //创建默认的 HttpClient 实例              HttpClient httpClient = new DefaultHttpClient();              try {                  //创建 httpUriRequest 实例                  HttpGet httpGet = new HttpGet("http://www.apache.org/");                  System.out.println("uri=" + httpGet.getURI());  

                //执行 get 请求                  HttpResponse httpResponse = httpClient.execute(httpGet);  

                //获取响应实体                  HttpEntity httpEntity = httpResponse.getEntity();                  //打印响应状态                  System.out.println(httpResponse.getStatusLine());                  if (httpEntity != null) {                      //响应内容的长度                      long length = httpEntity.getContentLength();                      //响应内容                      String content = EntityUtils.toString(httpEntity);  

                    System.out.println("Response content length:" + length);                      System.out.println("Response content:" + content);                  }  

                //有些教程里没有下面这行                  httpGet.abort();              } catch (Exception e) {                  e.printStackTrace();              } finally {                  //关闭连接,释放资源                  httpClient.getConnectionManager().shutdown();              }          }      }  

执行结果:
[img]http://dl.iteye.com/upload/attachment/584532/38d19a0e-b98f-3d13-a209-fcff5105bcb7.png[/img]

[b]httpget.setHeader[/b]
1:分析请求包中这六个头信息
[img]http://dl.iteye.com/upload/attachment/584558/ab5b639c-8f24-394e-a74a-ab0b1dd4f2b5.png[/img]
2:代码

       public static void main(String[] args) {          HttpClient httpClient = new DefaultHttpClient();          try {              HttpGet httpget = new HttpGet("http://www.iteye.com");  

            httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");              httpget.setHeader("Accept-Language", "zh-cn,zh;q=0.5");              httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1)");              httpget.setHeader("Accept-Encoding", "gzip, deflate");              httpget.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");              httpget.setHeader("Host", "www.iteye.com");              httpget.setHeader("Connection", "Keep-Alive");  

            HttpResponse response = httpClient.execute(httpget);              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("----------------------------------------");  

            InputStream inSm = entity.getContent();              Scanner inScn = new Scanner(inSm);              while (inScn.hasNextLine()) {                  System.out.println(inScn.nextLine());              }              // Do not feel like reading the response body              // Call abort on the request object              httpget.abort();          } catch (Exception e) {              e.printStackTrace();          } finally {              // When HttpClient instance is no longer needed,              // shut down the connection manager to ensure              // immediate deallocation of all system resources              httpClient.getConnectionManager().shutdown();          }      }  

3:效果[img]http://dl.iteye.com/upload/attachment/584560/6c810c00-ed43-3260-b650-6e6f2d2e1486.png[/img]
以上乱码是由于
[color=darkred]httpget.setHeader("Accept-Encoding", "gzip, deflate");[/color]
注释掉这行就行

[b]用post方法访问本地应用根据传递参数不同,返回不同结果[/b]
1:web.xml

    <servlet>          <servlet-name>Test1Servlet</servlet-name>          <servlet-class>demo.servlet.Test1Servlet</servlet-class>      </servlet>      <servlet-mapping>          <servlet-name>Test1Servlet</servlet-name>          <url-pattern>/test1Servlet</url-pattern>      </servlet-mapping>  

2:Test1Servlet.java

public class Test1Servlet extends HttpServlet {      @Override      protected void doPost(HttpServletRequest request, HttpServletResponse response)              throws ServletException, IOException {          //接收地址栏参数          String param1 = request.getParameter("param1");          //输出          response.setContentType("text/html;charset=UTF-8");          PrintWriter out = response.getWriter();          out.write("你传递来的参数param1=" + param1);          out.close();      }  } 

3:Demo2.java

public class Demo2 {  

    /**      * 用post方法访问本地应用根据传递参数不同,返回不同结果      *      * @param args      */      public static void main(String[] args) {          //创建默认的 HttpClient 实例          HttpClient httpClient = new DefaultHttpClient();  

        HttpPost httpPost = new HttpPost("http://localhost:86/test1Servlet");  

        List<NameValuePair> formParams = new ArrayList<NameValuePair>();          formParams.add(new BasicNameValuePair("param1", "刘文涛"));          UrlEncodedFormEntity urlEncodedFormEntity;  

        try {              urlEncodedFormEntity = new UrlEncodedFormEntity(formParams, "UTF-8");              httpPost.setEntity(urlEncodedFormEntity);              System.out.println("execurting request:" + httpPost.getURI());              HttpResponse httpResponse = null;              httpResponse = httpClient.execute(httpPost);              HttpEntity httpEntity = httpResponse.getEntity();              if (httpEntity != null) {                  String content = EntityUtils.toString(httpEntity, "UTF-8");                  System.out.println("Response content:" + content);              }          } catch (ClientProtocolException e) {              e.printStackTrace();          } catch (UnsupportedEncodingException e) {              e.printStackTrace();          } catch (IOException e) {              e.printStackTrace();          } finally {              //关闭连接,释放资源              httpClient.getConnectionManager().shutdown();          }      }  }  

结果:[img]http://dl.iteye.com/upload/attachment/0062/3722/d493017f-691c-39b0-ad45-03f86db6bde0.png[/img]

HttpClient 实例(1)相关推荐

  1. 【已更新实例】Java网络爬虫-HttpClient工具类

    关于用Java进行爬虫的资料网上实在少之又少,但作为以一名对Java刚刚初窥门径建立好兴趣的学生怎么能静得下心用新学的Python去写,毕竟Java是世界上最好的语言嘛 (狗头) 关于Java爬虫最受 ...

  2. HttpClient的一种简单实现Demo

    1 /** 2 * 测试HttpClient2种请求网络方式的Activity 3 * get和post 4 * 5 */ 6 public class HttpClientActivity exte ...

  3. httpclient get post

    https://www.cnblogs.com/wutongin/p/7778996.html post请求方法和get请求方法package com.xkeshi.paymentweb.contro ...

  4. HttpClient 详解一《C#高级编程(第9版)》

    1.异步调用 Web 服务 static void Main(string[] args){Console.WriteLine("In main before call to GetData ...

  5. 通过HTTPS使用HttpClient信任所有证书

    最近在Https上发布了有关HttpClient的问题( 在此处找到 ). 我取得了一些进展,但遇到了新问题. 与我的最后一个问题一样,我似乎找不到任何适合我的示例. 基本上,我希望我的客户端接受任何 ...

  6. Android网络优化之HttpClient

    参考:http://blog.csdn.net/heng615975867/article/details/9012303     尽管Android官网推荐在2.3及后续版本中使用HttpURLCo ...

  7. HttpClient 教程 (二)

    转自:http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2112832.html 第二章 连接管理 HttpClient有一个对连接初始化和终 ...

  8. HttpClient模拟http请求

    最近工作中使用到了两个jar包 httpclient.jar, httpcore.jar HttpClient 的 abort(终止)程序示例 [java] view plaincopyprint? ...

  9. Java开发小技巧(五):HttpClient工具类

    前言 大多数Java应用程序都会通过HTTP协议来调用接口访问各种网络资源,JDK也提供了相应的HTTP工具包,但是使用起来不够方便灵活,所以我们可以利用Apache的HttpClient来封装一个具 ...

最新文章

  1. element的滚动去掉横向_textarea去掉滚动条 textarea横向或纵向滚动条的去掉方法
  2. C#使用Win32API获得窗口和控件的句柄
  3. java面试题:集合_Java:选择正确的集合
  4. java中exception_Java中的异常 Exceptions
  5. linux 内核 ide,Linux设备驱动程序学习(7)-内核的数据类型
  6. 【SICP练习】102 练习2.79-2.80
  7. 【PL/SQL】PL/SQL语言基础
  8. 09年杀毒软件大比拼
  9. 第二篇:傅里叶变换与短时傅里叶变换
  10. 数字代理在持续由内而外重塑创新
  11. java商品销售管理系统_基于SSM框架下的JAVA商场销售管理系统
  12. keepalived IP漂移技术
  13. xubuntu装macos未能与服务器,macbook 安装ubuntu(Xubuntu)完整攻略
  14. Typora1.0.2 + SMMS上传图片
  15. 色彩系列教程(2):色系和色调
  16. 【JY】浅谈混凝土结构/构件性能试验指标概念(二)
  17. 希尔伯特变换(Hilbert Transform)
  18. Isight2019 集成MATLAB2019 (64位)的优化问题
  19. JAVA基础常见的知识点
  20. 180209 逆向-Frida-python on win多进程BUG(曲线救国)

热门文章

  1. 免费就业推荐与招聘,只为聚人气——2008年8月开放职位汇总
  2. Docsify Markdown表格列宽自定义
  3. Windows 下编译Realease版Chromium报UnicodeDecodeError错误
  4. Visual Studio Enterprise 2019序列号
  5. SpringCloud微服务简介(一)
  6. 有源医疗器械的开发过程和各阶段的注意事项(五)
  7. 不要关闭你的判断力引擎
  8. java 卫语句_Java规约-卫语句(guard clauses)
  9. 运维面试最后,你还有什么要问 本人回答
  10. IT技术面试官教你写面试简历