Android之Http沟通——4.Android HTTP索取信息:HttpClient
2015-09-27 20:16
671 查看
本节介绍:
他谈到了部分HttpURLConnection。本节HttpClient该,Apache为我们提供HttpClient(简单的Http客户端),只是毕竟不是亲儿子。HttpClient在API 21版本号后就给Google弃用了。而我们实际开发中。非常多页面都不是通过一个简单的URL就能够訪问的,可能须要登陆或者相关权限才干够訪问,这就涉及到了Session,Cookie等的问题了;当然我们能够用HttpURLConnection来实现,可是有点麻烦。而用HttpClient能够简单点。HttpClient用于接收/发送Http请求/响应。但不缓存server响应,不执行HTML页面潜入的JS代码,不会对页面内容进行不论什么解析。处理;要改掉废话太多的习惯,SO简化博文,開始本节内容吧:
HttpClient使用流程:
基本流程:HttpClient使用演示样例:
1.发送GET请求
嗯,就写个简单的发送GET请求的代码吧:package com.example.httpclientdemo; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebView; import android.widget.Button; public class MainActivity extends Activity implements OnClickListener { private Button btnGet; private WebView wView; public static final int SHOW_DATA = 0X123; private String detail = ""; private Handler handler = new Handler() { public void handleMessage(Message msg) { if(msg.what == SHOW_DATA) { wView.loadDataWithBaseURL("",detail, "text/html","UTF-8",""); } }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); setView(); } private void initView() { btnGet = (Button) findViewById(R.id.btnGet); wView = (WebView) findViewById(R.id.wView); } private void setView() { btnGet.setOnClickListener(this); wView.getSettings().setDomStorageEnabled(true); } @Override public void onClick(View v) { if (v.getId() == R.id.btnGet) { GetByHttpClient(); } } private void GetByHttpClient() { new Thread() { public void run() { try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://www.w3cschool.cc/python/python-tutorial.html"); HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { HttpEntity entity = httpResponse.getEntity(); detail = EntityUtils.toString(entity, "utf-8"); handler.sendEmptyMessage(SHOW_DATA); } } catch (Exception e) { e.printStackTrace(); } }; }.start(); } }
另外。假设是带有參数的GET请求的话,我们能够把參数放到List集合中,在对參数进行URL编码:
然后和URL拼接
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>(); params.add(new BasicNameValuePair("user", "猪小弟")); params.add(new BasicNameValuePair("pawd", "123")); String param = URLEncodedUtils.format(params, "UTF-8"); HttpGet httpGet = new HttpGet("http://www.baidu.com"+"?"+param);
接着贴下执行截图:
2.发送POST请求
POST请求比GET略微复杂一点。创建完HttpPost对象后,通过NameValuePair集合来存储等待提交的參数。并将參数传递到UrlEncodedFormEntity中,最后调用setEntity(entity)完毕,
HttpClient.execute(HttpPost)就可以。这里就不写样例了。临时没找到Post的站点,又不想
自己写个Servlet。So,直接贴核心代码吧~
核心代码:
private void PostByHttpClient(final String url) { new Thread() { public void run() { try{ HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("user", "猪大哥")); params.add(new BasicNameValuePair("pawd", "123")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,"UTF-8"); httpPost.setEntity(entity); HttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { HttpEntity entity2 = httpResponse.getEntity(); detail = EntityUtils.toString(entity2, "utf-8"); handler.sendEmptyMessage(SHOW_DATA); } }catch(Exception e){e.printStackTrace();} }; }.start(); }
3.胡说八道
事实上关于HttpClient的样例有非常多。比方笔者以前用它来抓学校教务系统上学生的课程表:这就涉及到Cookie,模拟登陆的东西,说到抓数据(爬虫)。一般我们是搭配着JSoup来解析
抓到数据的,有兴趣能够自己查阅相关文档。至于笔者的毕设,代码非常烂的说。兴许有时间
整理在公布出来吧。这里贴下模拟登陆教务系统部分的代码。大家能够体会下HttpClient:
//获得链接,模拟登录的实现: public int getConnect(String user, String key) throws Exception { // 先发送get请求 获取cookie值和__ViewState值 HttpGet getLogin = new HttpGet(true_url); // 第一步:基本的HTML: String loginhtml = ""; HttpResponse loginResponse = new DefaultHttpClient().execute(getLogin); if (loginResponse.getStatusLine().getStatusCode() == 200) { HttpEntity entity = loginResponse.getEntity(); loginhtml = EntityUtils.toString(entity); // 获取响应的cookie值 cookie = loginResponse.getFirstHeader("Set-Cookie").getValue(); System.out.println("cookie= " + cookie); } // 第二步:模拟登录 // 发送Post请求,禁止重定向 HttpPost httpPost = new HttpPost(true_url); httpPost.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false); // 设置Post提交的头信息的參数 httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"); httpPost.setHeader("Referer", true_url); httpPost.setHeader("Cookie", cookie); // 设置请求数据 List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("__VIEWSTATE", getViewState(loginhtml)));// __VIEWSTATE參数,假设变化能够动态抓取获取 params.add(new BasicNameValuePair("Button1", "")); params.add(new BasicNameValuePair("hidPdrs", "")); params.add(new BasicNameValuePair("hidsc", "")); params.add(new BasicNameValuePair("lbLanguage", "")); params.add(new BasicNameValuePair("RadioButtonList1", "%D1%A7%C9%FA")); params.add(new BasicNameValuePair("txtUserName", user)); params.add(new BasicNameValuePair("TextBox2", key)); params.add(new BasicNameValuePair("txtSecretCode", "")); // ( ╯□╰ )逗比正方,居然不须要验证码 // 设置编码方式,响应请求,获取响应状态码: httpPost.setEntity(new UrlEncodedFormEntity(params, "gb2312")); HttpResponse response = new DefaultHttpClient().execute(httpPost); int Status = response.getStatusLine().getStatusCode(); if(Status == 200)return Status; System.out.println("Status= " + Status); // 重定向状态码为302 if (Status == 302 || Status == 301) { // 获取头部信息中Location的值 location = response.getFirstHeader("Location").getValue(); System.out.println(location); // 第三步:获取管理信息的主页面 // Get请求 HttpGet httpGet = new HttpGet(ip_url + location);// 带上location地址訪问 httpGet.setHeader("Referer", true_url); httpGet.setHeader("Cookie", cookie); // 主页的html mainhtml = ""; HttpResponse httpResponseget = new DefaultHttpClient() .execute(httpGet); if (httpResponseget.getStatusLine().getStatusCode() == 200) { HttpEntity entity = httpResponseget.getEntity(); mainhtml = EntityUtils.toString(entity); } } return Status; }
总结:
好的,本节关于HttpClient就到这里吧,内容还是比較简单的~
下节我们将使用retrofit来封装我们的HTTP请求。敬请期待~
对了,关于Android里简单的网络技术能够參考小猪之前写过的入门系列:
小猪的Android入门之路 day 8 part 3
相关文章推荐
- 【2015/9/27】Linux学习日志_Day2 终端命令 一些网络命令
- 黑马程序员——网络编程
- HDU 5478 Can you find it 2015ICPC上海网络赛
- HDU 5492 Find a path (dp) 2015合肥网络赛
- 大型网站的 HTTPS 实践(1):HTTPS 协议和原理
- Linux网络编程---I/O多路复用 之 select
- HDU 5475 An easy problem 2015ICPC 上海网络赛
- 传智播客c/c++公开课学习笔记--Linux网络流媒体服务器的核心代码揭秘
- TCP基础
- HTTPD 工作原理
- Xcode7 使用NSURLSession发送HTTP请求报错
- OpenStack OVS GRE/VXLAN网络
- Http服务器实现文件上传与下载(二)
- TCP、UDP、IP 协议分析
- UEditor富文本编辑器的图片上传 http://fex.baidu.com/ueditor/#server-deploy
- solr限制admin界面访问(端口限制和http授权限制)
- WinHttpOpenRequest第6个参数如何传?LPCWSTR*
- HTTP中的Cookie
- HttpServletRequest.getParameter()出现乱码现象解决方案
- 对现有的所能找到个DDOS代码(攻击模块)做出一次分析----TCP篇