新版HttpClient4.2与之前的3.x版本有了很大变化,建议从http://hc.apache.org/处以得到最新的信息。

  1. 关于HttpCore与HttpClient:HttpCore是位于HTTP传输组件的底层包,可以用来简化HTTP客户端与服务器端的开发。HttpClient是一个符合HTTP1.1版本,基于HttpCore类包的一个实现。它同时为客户端认证、HTTP状态管理、HTTP连接管理提供了可重用的客户端组件。HttpCore类包目前最新发布版本是httpcore-4.2.4;HttpClient类包的版本是httpclient-4.2.5。
    了解到HttpCore包与HttpClient包的差别,在程序中就应该大致知道一些包它们存在于哪个类库中。比如:org.apache.http包属于HttpCore,而org.apache.http.client包属于HttpClient。
  2. HttpClient的API文档在下载的zip中已经包括;
    HttpCore的API文档可以参考:http://hc.apache.org/httpcomponents-core-4.2.x/httpcore/apidocs/index.html
  3. HttpClient4.2需要Java 5.0及以上版本;需要支持包有(下载zip包中已经包括):
    * Apache HttpComponents HttpCore
    * Apache Commons Logging
    * Apache Commons Codec

获取一个HTML页面的内容,一个简单的get应用

    // 获取一个HTML页面的内容,一个简单的get应用public void grabPageHTML() throws Exception {HttpClient httpclient = new DefaultHttpClient();HttpGet httpget = new HttpGet("http://www.baidu.com/");HttpResponse response = httpclient.execute(httpget);HttpEntity entity = response.getEntity();String html = EntityUtils.toString(entity, "GBK");// releaseConnection等同于reset,作用是重置request状态位,为下次使用做好准备。// 其实就是用一个HttpGet获取多个页面的情况下有效果;否则可以忽略此方法。
        httpget.releaseConnection();System.out.println(html);}

下载一个文件到本地(本示范中为一个验证码图片)

    // 下载一个文件到本地(本示范中为一个验证码图片)public void downloadFile() throws Exception {String url = "http://www.lashou.com/account/captcha";String destfilename = "D:\\TDDOWNLOAD\\yz.png";HttpClient httpclient = new DefaultHttpClient();HttpGet httpget = new HttpGet(url);File file = new File(destfilename);if (file.exists()) {file.delete();}HttpResponse response = httpclient.execute(httpget);HttpEntity entity = response.getEntity();InputStream in = entity.getContent();try {FileOutputStream fout = new FileOutputStream(file);int l = -1;byte[] tmp = new byte[2048]; while ((l = in.read(tmp)) != -1) {fout.write(tmp);} fout.close();} finally {// 在用InputStream处理HttpEntity时,切记要关闭低层流。
            in.close();}httpget.releaseConnection();}

Post方法,模拟表单提交参数登录到网站并打开会员页面获取内容(会话保持)

    // Post方法,模拟表单提交参数登录到网站。// 结合了上面两个方法:grabPageHTML/downloadFile,同时增加了Post的代码。public void login2Lashou() throws Exception {// 第一步:先下载验证码到本地String url = "http://www.lashou.com/account/captcha";String destfilename = "D:\\TDDOWNLOAD\\yz.png";HttpClient httpclient = new DefaultHttpClient();HttpGet httpget = new HttpGet(url);File file = new File(destfilename);if (file.exists()) {file.delete();}HttpResponse response = httpclient.execute(httpget);HttpEntity entity = response.getEntity();InputStream in = entity.getContent();try {FileOutputStream fout = new FileOutputStream(file);int l = -1;byte[] tmp = new byte[2048]; while ((l = in.read(tmp)) != -1) {fout.write(tmp);} fout.close();} finally {in.close();}httpget.releaseConnection();// 第二步:用Post方法带若干参数尝试登录,需要手工输入下载验证码中显示的字母、数字BufferedReader br = new BufferedReader(new InputStreamReader(System.in));System.out.println("请输入下载下来的验证码中显示的数字...");String yan = br.readLine();HttpPost httppost = new HttpPost("http://www.lashou.com/account/login/");List<NameValuePair> params = new ArrayList<NameValuePair>();params.add(new BasicNameValuePair("user_id", "testuser007"));params.add(new BasicNameValuePair("pwd", "asdfg123"));params.add(new BasicNameValuePair("yan", yan));params.add(new BasicNameValuePair("save_user", "on"));params.add(new BasicNameValuePair("save_pwd", "on"));params.add(new BasicNameValuePair("sub", "登录"));httppost.setEntity(new UrlEncodedFormEntity(params));response = httpclient.execute(httppost);entity = response.getEntity();// 在这里可以用Jsoup之类的工具对返回结果进行分析,以判断登录是否成功String postResult = EntityUtils.toString(entity, "GBK"); // 我们这里只是简单的打印出当前Cookie值以判断登录是否成功。List<Cookie> cookies = ((AbstractHttpClient)httpclient).getCookieStore().getCookies();for(Cookie cookie: cookies)System.out.println(cookie);httppost.releaseConnection();// 第三步:打开会员页面以判断登录成功(未登录用户是打不开会员页面的)String memberpage = "http://www.lashou.com/account/orders/";httpget = new HttpGet(memberpage);response = httpclient.execute(httpget); // 必须是同一个HttpClient!entity = response.getEntity();String html = EntityUtils.toString(entity, "GBK");httpget.releaseConnection();System.out.println(html);}

输出:

请输入下载下来的验证码中显示的数字...
sbzq
...

[version: 0][name: login_name2][value: testuser007][domain: www.lashou.com][path: /][expiry: Mon Sep 09 10:21:19 CST 2013]
[version: 0][name: pwd2][value: 4c88a4062736c26572d3ec382868fa2b][domain: lashou.com][path: /][expiry: Mon Sep 09 10:21:19 CST 2013]
?<!doctype html>

...

设置代理服务器

    // 设置代理服务器public void testProxy() throws Exception {HttpHost proxy = new HttpHost("127.0.0.1", 8888);// 方式一HttpClient httpclient = new DefaultHttpClient();httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);// 方式二HttpParams params = new BasicHttpParams(); params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);HttpClient httpclient1 = new DefaultHttpClient(params);}

几种常用HTTP头的设置

    // 几种常用HTTP头的设置public void testBasicHeader() throws Exception {HttpParams params = new BasicHttpParams(); Collection<BasicHeader> collection = new ArrayList<BasicHeader>();collection.add(new BasicHeader("Accept", "text/html, application/xhtml+xml, */*"));collection.add(new BasicHeader("Referer", "http://www.sina.com/"));collection.add(new BasicHeader("Accept-Language", "zh-CN"));collection.add(new BasicHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)"));collection.add(new BasicHeader("Accept-Encoding", "gzip, deflate"));params.setParameter(ClientPNames.DEFAULT_HEADERS, collection);HttpClient httpclient = new DefaultHttpClient(params);// 下面内容略}

多线程编程下的线程池设置

    // 多线程编程下的线程池设置(这点在需要登录且用一个HttpClient对象抓取多个页面的情况下特别有用)public void testConnectionManager() throws Exception {// 连接池设置SchemeRegistry schemeRegistry = new SchemeRegistry();schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);cm.setMaxTotal(200); // 连接池里的最大连接数cm.setDefaultMaxPerRoute(20); // 每个路由的默认最大连接数HttpHost localhost = new HttpHost("locahost", 80); // 可以针对某特定网站指定最大连接数cm.setMaxPerRoute(new HttpRoute(localhost), 30);// 其它设置HttpParams params = new BasicHttpParams(); params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);HttpClient httpclient = new DefaultHttpClient(cm, params);// 下面内容略}

测试HTTP上下文对象(HttpContext)

    // 测试HTTP上下文对象(HttpContext)public void testContext() throws Exception {// 请求一个页面,然后解析各上下文对象DefaultHttpClient httpclient = new DefaultHttpClient();HttpContext localContext = new BasicHttpContext();HttpGet httpget = new HttpGet("http://www.baidu.com/");HttpResponse response = httpclient.execute(httpget, localContext);// the actual connection to the target server.HttpConnection conn = (HttpConnection) localContext.getAttribute(ExecutionContext.HTTP_CONNECTION);  System.out.println("Socket timeout: " + conn.getSocketTimeout());  // the connection targetHttpHost target = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);System.out.println("Final target: " + target);// the connection proxy, if used HttpHost proxy = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_PROXY_HOST);if (proxy != null)System.out.println("Proxy host/port: " + proxy.getHostName() + "/"+ proxy.getPort());// the actual HTTP requestHttpRequest request = (HttpRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST);System.out.println("HTTP version: " + request.getProtocolVersion());Header[] headers = request.getAllHeaders();System.out.println("HTTP Headers: ");for (Header header : headers) {System.out.println("\t" + header.getName() + ": " + header.getValue());}System.out.println("HTTP URI: " + request.getRequestLine().getUri());// the actual HTTP responseresponse = (HttpResponse) localContext.getAttribute(ExecutionContext.HTTP_RESPONSE);HttpEntity entity = response.getEntity();if (entity != null) {System.out.println("Content Encoding:" + entity.getContentEncoding());System.out.println("Content Type:" + entity.getContentType());}// the flag indicating whether the actual request has been fully transmitted to the connection target. System.out.println("Sent flag: " + localContext.getAttribute(ExecutionContext.HTTP_REQ_SENT));// 如果没有用到返回entity中的内容,那么要把它消费掉,以保证底层的资源得以释放。entity = response.getEntity();EntityUtils.consume(entity);}    

输出:

Socket timeout: 0
Final target: http://www.baidu.com
HTTP version: HTTP/1.1
HTTP Headers: 
    Host: www.baidu.com
    Connection: Keep-Alive
    User-Agent: Apache-HttpClient/4.2.5 (java 1.5)
HTTP URI: /
Content Encoding:null
Content Type:Content-Type: text/html;charset=utf-8
Sent flag: true

java httpclient 模拟登录相关推荐

  1. JAVA使用HttpClient模拟登录正方教务系统,爬取学籍信息和课程表成绩等,超详细登录分析和代码注解

    目录 前言 分析 代码实现 第一次GET POST登录 第二次Get 第三次GET 第四次GET 第五次GET 测试 完整代码 前言 最近在做一个APP,需要获取我们学校--武汉纺织大学皇家停水断电断 ...

  2. Java爬虫模拟登录——不给我毛概二的H某大学

    你的账号访问太频繁,请一分钟之后再试! 从大一开始 就用脚本在刷课 在专业课踢的只剩下一门C#的情况下 活活刷到一周的课 大二开始教务系统多了一个非常**的操作 退课池 and 访问频繁缓冲 难道,我 ...

  3. HttpClient模拟登录、HtmlUnit模拟登录,jsoup爬取登录后的内容(不带验证码)

    一.HttpClient模拟登录是通过post或get请求,登录后抓取的是静态页面,动态页面使用HtmlUnit public static void main(String[] args) thro ...

  4. Java使用HttpClient模拟登录微博

    前言 前几天刚刚接触了Java这边的关于HTTP的一个工具包-HttpClient , 那么就想借此机会练练手, 用这个工具进行对微博的模拟登录, 简单的获取一下微博的数据 , 但是大家可以不必执着于 ...

  5. HttpClient 模拟登录Web版新浪微博

    上篇介绍了如何模拟登录手机版微博,过程还是比较简单的,没有设计到复杂的加密部分. 登录Web版微博的过程还是一样的,只不过这次需要提交的数据多一点. public static Cookie[] ge ...

  6. java实现模拟登录新浪微博

    最近做新浪微博的数据挖掘,遇到不少的问题,搜索了不少的网上资源,现在我来总结一下,希望对大家有所帮助: 1.准备工作 只是登录无需申请新浪和腾迅的开发者账号,如果需要发送微博功能,需要申请一个新浪和腾 ...

  7. HttpClient 模拟登录手机版新浪微博

    手机版微博单点登录的URL为:http://3g.sina.com.cn/prog/wapsite/sso/login.php 我们先来看一下这个网页源代码: <html><head ...

  8. java模拟登录知乎_Android(Java) 模拟登录知乎并抓取用户信息

    前不久.看到一篇文章我用爬虫一天时间"偷了"知乎一百万用户.仅仅为证明PHP是世界上最好的语言,该文章中使用的登录方式是直接复制cookie到代码中,这里呢,我不以爬信息为目的.仅 ...

  9. HttpClient 模拟登录网易微博

          实现核心:代码执行流程,根据抓包工具,模拟浏览器请求步骤走       private static void testLogin()       {             try    ...

最新文章

  1. Allan方差分析方法的直观理解
  2. Golang的interface实践
  3. RabbitMQ 一二事(2) - 工作队列使用
  4. 科大星云诗社动态20210410
  5. commonJs原理解析
  6. Vue简单封装axios—解决post请求后端接收不到参数问题
  7. 避免延迟的JPA集合
  8. 【信号与系统】系统特性
  9. 建议你一定要尝试的副业排名TOP1
  10. 创建使用模块与datetime模块使用
  11. 转:error LNK2001 错误
  12. 了解Linux操作系统的引导过程
  13. 5款Windows系统下的桌面管理软件
  14. 怎么提高文公写作水平?公文写作报告类模板
  15. 中兴e9000服务器,ZXCTN 9000-E设备系列_ZXCTN 9000-E系列中兴传输设备_中兴设备 - 诺深达华为光端机...
  16. 机器学习笔记 - 使用Face recognition、OpenCV、Python进行人脸识别
  17. I210 网卡设定 force link mode 并关闭 EEE mode
  18. 美国国立卫生研究院利用AI自动检测肺部异常,突破数据收集瓶颈
  19. java 音频 合成_java实现mp3合并的方法
  20. CANoe 入门 Step by step系列(二)CAPL编程

热门文章

  1. M1卡id号的计算算法
  2. 简介 几种破解哈希加密的方法
  3. SHP转化成JSON
  4. Tarjan 求有向图的强连通分量
  5. 思科DHCP配置命令
  6. 【软考-软件设计师】(下午题).
  7. api之removeAll()使用避坑
  8. 批处理调用cacls修改文件权限
  9. GEE:对Sentinel-2遥感影像进行处理,水体提取与可视化
  10. 《flask日志logging一》flask官网介绍logging