[关闭]
@coder-pig 2015-09-08T02:14:30.000000Z 字数 6337 阅读 1627

Android基础入门教程——7.1.4 Android HTTP请求方式:HttpClient

Android基础入门教程


本节引言:

在上一节中我们对HttpURLConnection进行了学习,本节到第二种方式:HttpClient,尽管被Google
弃用了,但是我们我们平时也可以拿HttpClient来抓下包,配合Jsoup解析网页效果更佳!HttpClient
用于接收/发送Http请求/响应,但不缓存服务器响应,不执行HTML页面潜入的JS代码,不会对页面内容
进行任何解析,处理!开始本节内容!


1.HttpClient使用流程

基本流程


2.HttpClient使用示例

1)使用HttpClient发送GET请求

直接贴下简单的发送Get请求的代码:

  1. public class MainActivity extends Activity implements OnClickListener {
  2. private Button btnGet;
  3. private WebView wView;
  4. public static final int SHOW_DATA = 0X123;
  5. private String detail = "";
  6. private Handler handler = new Handler() {
  7. public void handleMessage(Message msg) {
  8. if(msg.what == SHOW_DATA)
  9. {
  10. wView.loadDataWithBaseURL("",detail, "text/html","UTF-8","");
  11. }
  12. };
  13. };
  14. @Override
  15. protected void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.activity_main);
  18. initView();
  19. setView();
  20. }
  21. private void initView() {
  22. btnGet = (Button) findViewById(R.id.btnGet);
  23. wView = (WebView) findViewById(R.id.wView);
  24. }
  25. private void setView() {
  26. btnGet.setOnClickListener(this);
  27. wView.getSettings().setDomStorageEnabled(true);
  28. }
  29. @Override
  30. public void onClick(View v) {
  31. if (v.getId() == R.id.btnGet) {
  32. GetByHttpClient();
  33. }
  34. }
  35. private void GetByHttpClient() {
  36. new Thread()
  37. {
  38. public void run()
  39. {
  40. try {
  41. HttpClient httpClient = new DefaultHttpClient();
  42. HttpGet httpGet = new HttpGet("http://www.w3cschool.cc/python/python-tutorial.html");
  43. HttpResponse httpResponse = httpClient.execute(httpGet);
  44. if (httpResponse.getStatusLine().getStatusCode() == 200) {
  45. HttpEntity entity = httpResponse.getEntity();
  46. detail = EntityUtils.toString(entity, "utf-8");
  47. handler.sendEmptyMessage(SHOW_DATA);
  48. }
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. }
  52. };
  53. }.start();
  54. }
  55. }

运行截图

另外,如果是带有参数的GET请求的话,我们可以将参数放到一个List集合中,再对参数进行URL编码,
最后和URL拼接下就好了:

  1. List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
  2. params.add(new BasicNameValuePair("user", "猪小弟"));
  3. params.add(new BasicNameValuePair("pawd", "123"));
  4. String param = URLEncodedUtils.format(params, "UTF-8");
  5. HttpGet httpGet = new HttpGet("http://www.baidu.com"+"?"+param);

2)使用HttpClient发送POST请求

POST请求比GET稍微复杂一点,创建完HttpPost对象后,通过NameValuePair集合来存储等待提交
的参数,并将参数传递到UrlEncodedFormEntity中,最后调用setEntity(entity)完成,
HttpClient.execute(HttpPost)即可;这里就不写例子了,暂时没找到Post的网站,又不想
自己写个Servlet,So,直接贴核心代码吧~

核心代码:

  1. private void PostByHttpClient(final String url)
  2. {
  3. new Thread()
  4. {
  5. public void run()
  6. {
  7. try{
  8. HttpClient httpClient = new DefaultHttpClient();
  9. HttpPost httpPost = new HttpPost(url);
  10. List<NameValuePair> params = new ArrayList<NameValuePair>();
  11. params.add(new BasicNameValuePair("user", "猪大哥"));
  12. params.add(new BasicNameValuePair("pawd", "123"));
  13. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,"UTF-8");
  14. httpPost.setEntity(entity);
  15. HttpResponse httpResponse = httpClient.execute(httpPost);
  16. if (httpResponse.getStatusLine().getStatusCode() == 200) {
  17. HttpEntity entity2 = httpResponse.getEntity();
  18. detail = EntityUtils.toString(entity2, "utf-8");
  19. handler.sendEmptyMessage(SHOW_DATA);
  20. }
  21. }catch(Exception e){e.printStackTrace();}
  22. };
  23. }.start();
  24. }

3.HttpClient抓数据示例(教务系统数据抓取)

其实关于HttpClient的例子有很多,比如笔者曾经用它来抓学校教务系统上学生的课程表:
这就涉及到Cookie,模拟登陆的东西,说到抓数据(爬虫),一般我们是搭配着JSoup来解析
抓到数据的,有兴趣可以自己查阅相关资料,这里贴下笔者毕设app里获取网页部分的关键
代码!大家可以体会下:

HttpClient可以通过下述代码获取与设置Cookie:
HttpResponse loginResponse = new DefaultHttpClient().execute(getLogin);
获得Cookie:cookie = loginResponse.getFirstHeader("Set-Cookie").getValue();
请求时带上Cookie**:httpPost.setHeader("Cookie", cookie);**

  1. //获得链接,模拟登录的实现:
  2. public int getConnect(String user, String key) throws Exception {
  3. // 先发送get请求 获取cookie值和__ViewState值
  4. HttpGet getLogin = new HttpGet(true_url);
  5. // 第一步:主要的HTML:
  6. String loginhtml = "";
  7. HttpResponse loginResponse = new DefaultHttpClient().execute(getLogin);
  8. if (loginResponse.getStatusLine().getStatusCode() == 200) {
  9. HttpEntity entity = loginResponse.getEntity();
  10. loginhtml = EntityUtils.toString(entity);
  11. // 获取响应的cookie值
  12. cookie = loginResponse.getFirstHeader("Set-Cookie").getValue();
  13. System.out.println("cookie= " + cookie);
  14. }
  15. // 第二步:模拟登录
  16. // 发送Post请求,禁止重定向
  17. HttpPost httpPost = new HttpPost(true_url);
  18. httpPost.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
  19. // 设置Post提交的头信息的参数
  20. httpPost.setHeader("User-Agent",
  21. "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
  22. httpPost.setHeader("Referer", true_url);
  23. httpPost.setHeader("Cookie", cookie);
  24. // 设置请求数据
  25. List<NameValuePair> params = new ArrayList<NameValuePair>();
  26. params.add(new BasicNameValuePair("__VIEWSTATE",
  27. getViewState(loginhtml)));// __VIEWSTATE参数,如果变化可以动态抓取获取
  28. params.add(new BasicNameValuePair("Button1", ""));
  29. params.add(new BasicNameValuePair("hidPdrs", ""));
  30. params.add(new BasicNameValuePair("hidsc", ""));
  31. params.add(new BasicNameValuePair("lbLanguage", ""));
  32. params.add(new BasicNameValuePair("RadioButtonList1", "%D1%A7%C9%FA"));
  33. params.add(new BasicNameValuePair("txtUserName", user));
  34. params.add(new BasicNameValuePair("TextBox2", key));
  35. params.add(new BasicNameValuePair("txtSecretCode", "")); // ( ╯□╰ )逗比正方,竟然不需要验证码
  36. // 设置编码方式,响应请求,获取响应状态码:
  37. httpPost.setEntity(new UrlEncodedFormEntity(params, "gb2312"));
  38. HttpResponse response = new DefaultHttpClient().execute(httpPost);
  39. int Status = response.getStatusLine().getStatusCode();
  40. if(Status == 200)return Status;
  41. System.out.println("Status= " + Status);
  42. // 重定向状态码为302
  43. if (Status == 302 || Status == 301) {
  44. // 获取头部信息中Location的值
  45. location = response.getFirstHeader("Location").getValue();
  46. System.out.println(location);
  47. // 第三步:获取管理信息的主页面
  48. // Get请求
  49. HttpGet httpGet = new HttpGet(ip_url + location);// 带上location地址访问
  50. httpGet.setHeader("Referer", true_url);
  51. httpGet.setHeader("Cookie", cookie);
  52. // 主页的html
  53. mainhtml = "";
  54. HttpResponse httpResponseget = new DefaultHttpClient()
  55. .execute(httpGet);
  56. if (httpResponseget.getStatusLine().getStatusCode() == 200) {
  57. HttpEntity entity = httpResponseget.getEntity();
  58. mainhtml = EntityUtils.toString(entity);
  59. }
  60. }
  61. return Status;
  62. }

4.使用HttpPut发送Put请求

示例代码如下

  1. public static int PutActCode(String actCode, String licPlate, Context mContext) {
  2. int resp = 0;
  3. String cookie = (String) SPUtils.get(mContext, "session", "");
  4. HttpPut httpPut = new HttpPut(PUTACKCODE_URL);
  5. httpPut.setHeader("Cookie", cookie);
  6. try {
  7. List<NameValuePair> params = new ArrayList<NameValuePair>();
  8. params.add(new BasicNameValuePair("activation_code", actCode));
  9. params.add(new BasicNameValuePair("license_plate", licPlate));
  10. httpPut.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
  11. HttpResponse course_response = new DefaultHttpClient().execute(httpPut);
  12. if (course_response.getStatusLine().getStatusCode() == 200) {
  13. HttpEntity entity2 = course_response.getEntity();
  14. JSONObject jObject = new JSONObject(EntityUtils.toString(entity2));
  15. resp = Integer.parseInt(jObject.getString("status_code"));
  16. return resp;
  17. }
  18. } catch (Exception e) {
  19. e.printStackTrace();
  20. }
  21. return resp;
  22. }

本节小结:

好的,本节关于Android HTTP的第二种请求方式:HttpClient就到这里,
下节,我们来学习Android 4.4引入的OKHttp的简单使用!谢谢~

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注