本讲内容:URLConnection和HttpClient使用入门
在 Android中除了使用WebView控件访问网络以外,还有用代码方式访问网络的方法,代码方式有时候会显得更加灵活。本讲会介绍使用 URLConnection对象和HttpClient组件访问网络的方法。而这两种方法和Java Web开发中的使用方式几乎没有区别,而Web开发的相关资料比比皆是,因此有兴趣的同学学完本讲之后可以专门去研究一下HttpClient4.0的内 容,以求更深入的学习。
一、分别使用URLConnection和HttpClient访问Google天气服务的例子
这个例子的的目的就是从Google哪里获取郑州的天气预报信息,并显示在TextView中,本讲只会把返回的XML数据显示出来,下一讲我们学XML解析的时候再把这个天气预报做成图文并茂的形式,所以大家先暂时忍耐一下丑陋的界面。
1、新建一个项目 Lesson30_HttpClient ,主Activity的文件名是 MainActivity.java
2、res/layout/main.xml的内容如下:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <linearlayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
  3. <textview android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:id="@+id/TextView01"
    android:text="网络连接测试">
  4. <button android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:id="@+id/Button01"
    android:text="使用URLConnection访问GoogleWeatherAPI">
  5. </button>
  6. <button android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:id="@+id/Button02"
    android:text="使用HttpClient访问GoogleWeatherAPI">
  7. </button>
  8. <scrollview android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ScrollView01">
  9. <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/TextView02">
  10. </textview>
  11. </scrollview>
  12. </textview></linearlayout>

复制代码

3、MainActivity.java的内容如下:

  1. package android.basic.lesson30;
  2. import java.io.InputStreamReader;
  3. import java.net.HttpURLConnection;
  4. import java.net.URL;
  5. import org.apache.http.client.ResponseHandler;
  6. import org.apache.http.client.methods.HttpGet;
  7. import org.apache.http.impl.client.BasicResponseHandler;
  8. import org.apache.http.impl.client.DefaultHttpClient;
  9. import android.app.Activity;
  10. import android.os.Bundle;
  11. import android.view.View;
  12. import android.widget.Button;
  13. import android.widget.TextView;
  14. import android.widget.Toast;
  15. public class MainActivity extends Activity {
  16. TextView tv;
  17. String googleWeatherUrl1 = "http://www.google.com/ig/api?weather=zhengzhou";
  18. String googleWeatherUrl2 = "http://www.google.com/ig/api?hl=zh-cn&weather=zhengzhou";
  19. /** Called when the activity is first created. */
  20. @Override
  21. public void onCreate(Bundle savedInstanceState) {
  22. super.onCreate(savedInstanceState);
  23. setContentView(R.layout.main);
  24. // 定义UI组件
  25. Button b1 = (Button) findViewById(R.id.Button01);
  26. Button b2 = (Button) findViewById(R.id.Button02);
  27. tv = (TextView) findViewById(R.id.TextView02);
  28. // 设置按钮单击监听器
  29. b1.setOnClickListener(new View.OnClickListener() {
  30. @Override
  31. public void onClick(View v) {
  32. // 使用URLConnection连接GoogleWeatherAPI
  33. urlConn();
  34. }
  35. });
  36. // 设置按钮单击监听器
  37. b2.setOnClickListener(new View.OnClickListener() {
  38. @Override
  39. public void onClick(View v) {
  40. // 使用HttpCient连接GoogleWeatherAPI
  41. httpClientConn();
  42. }
  43. });
  44. }
  45. // 使用URLConnection连接GoogleWeatherAPI
  46. protected void urlConn() {
  47. try {
  48. // URL
  49. URL url = new URL(googleWeatherUrl1);
  50. // HttpURLConnection
  51. HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
  52. if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
  53. Toast.makeText(getApplicationContext(), "连接Google Weather API成功!",
  54. Toast.LENGTH_SHORT).show();
  55. // InputStreamReader
  56. InputStreamReader isr = new InputStreamReader(httpconn.getInputStream(), "utf-8");
  57. int i;
  58. String content = "";
  59. // read
  60. while ((i = isr.read()) != -1) {
  61. content = content + (char) i;
  62. }
  63. isr.close();
  64. //设置TextView
  65. tv.setText(content);
  66. }
  67. //disconnect
  68. httpconn.disconnect();
  69. } catch (Exception e) {
  70. Toast.makeText(getApplicationContext(), "连接Google Weather API失败", Toast.LENGTH_SHORT)
  71. .show();
  72. e.printStackTrace();
  73. }
  74. }
  75. // 使用HttpCient连接GoogleWeatherAPI
  76. protected void httpClientConn() {
  77. //DefaultHttpClient
  78. DefaultHttpClient httpclient = new DefaultHttpClient();
  79. //HttpGet
  80. HttpGet httpget = new HttpGet(googleWeatherUrl2);
  81. //ResponseHandler
  82. ResponseHandler<string> responseHandler = new BasicResponseHandler();
  83. try {
  84. String content = httpclient.execute(httpget, responseHandler);
  85. Toast.makeText(getApplicationContext(), "连接Google Weather API成功!",
  86. Toast.LENGTH_SHORT).show();
  87. //设置TextView
  88. tv.setText(content);
  89. } catch (Exception e) {
  90. Toast.makeText(getApplicationContext(), "连接Google Weather API失败", Toast.LENGTH_SHORT)
  91. .show();
  92. e.printStackTrace();
  93. }
  94. httpclient.getConnectionManager().shutdown();
  95. }
  96. }</string>

复制代码

4、
最后别忘了在AndroidManifest.xml中加入访问网络的权限,<uses-permission
android:name="android.permission.INTERNET"></uses-permission>5、
运行程序查看结果:

按第一个按钮的效果,返回的数据结果显示在了TextView里。

按第二个按钮的效果,返回的数据结果显示在了TextView里, 所不同的是显示的是中文。好了,本讲先到这里。

URLConnection和HttpClient使用入门的更多相关文章

  1. java学习-GET方式抓取网页(UrlConnection和HttpClient)

    抓取网页其实就是模拟客户端(PC端,手机端...)发送请求,获得响应数据documentation,解析对应数据的过程.---自己理解,错误请告知 一般常用请求方式有GET,POST,HEAD三种 G ...

  2. 《Android学习指南》目录

    源:<Android学习指南>目录 Android学习指南的内容分类: 分类 描述 0.学习Android必备的Java基础知识 没有Java基础的朋友,请不要先看Android的课程,这 ...

  3. 《Android学习指南》文件夹

    转自:http://android.yaohuiji.com/about Android学习指南的内容分类: 分类 描写叙述 0.学习Android必备的Java基础知识 没有Java基础的朋友,请不 ...

  4. 基于开源 Openfire 聊天服务器 - 开发Openfire聊天记录插件[转]

    上一篇文章介绍到怎么在自己的Java环境中搭建openfire插件开发的环境,同时介绍到怎样一步步简单的开发openfire插件.一步步很详细的介绍到简单插件开发,带Servlet的插件的开发.带JS ...

  5. openfire:基于开源 Openfire 聊天服务器 - 开发Openfire聊天记录插件

    基于开源 Openfire 聊天服务器 - 开发Openfire聊天记录插件 上一篇文章介绍到怎么在自己的Java环境中搭建openfire插件开发的环境,同时介绍到怎样一步步简单的开发openfir ...

  6. 基于开源 Openfire 聊天服务器 - 开发Openfire聊天记录插件

    原文:http://www.cnblogs.com/hoojo/archive/2013/03/29/openfire_plugin_chatlogs_plugin_.html 随笔-150  评论- ...

  7. 我的简历 PHP Java C# 技术总监

          石先生 ID:303321266 目前正在找工作 13611326258 hr_msn@163.com 男|32 岁 (1985/08/06)|现居住北京-海淀区|12年工作经验     ...

  8. java实现 HTTP/HTTPS请求绕过证书检测代码实现

    java实现 HTTP/HTTPS请求绕过证书检测代码实现 1.开发需求 需要实现在服务端发起HTTP/HTTPS请求,访问其他程序资源. 2.URLConnection和HTTPClient的比较 ...

  9. asp.net hessian + android hessdroid

    做android开发时你还在为gson,json而人肉序列化与反序列化吗,上传文件时你还在使用UrlConnection或者HttpClient吗?下面提供了asp.net 服务端与 android ...

随机推荐

  1. Js中split()方法的正确使用

    通过 js 获取 QueryString (location.search部分) 参数很常见,网上代码也满天飞.不过现在的框架,基本上都通过路由伪静态了,把以前的 QueryString 变成了pat ...

  2. sql中字符串如何比大小

    从字符串的第一个字符开始比较ASSCII码值,如果相等则看下一个,以此类推. 数字的ASCII码<大写字母的ASCII码<小写字母的ASCII码. ASCII码

  3. BootStrap同时显示多个Modal解决方案

    使用BootStrap自带的Modal的时候,如果同时调用多个Modal,那么只能看到背景颜色加深但是看不见新的Modal页面. 问题主要是Modal的z-index有问题,重新计算z-index并赋 ...

  4. 兼容安卓和ios实现一键复制内容到剪切板

    实现代码如下: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <m ...

  5. Multinoulli distribution

    https://www.statlect.com/probability-distributions/multinoulli-distribution3 Multinoulli distributio ...

  6. 【转】编程思想之多线程与多进程(3)——Java中的多线程

    <编程思想之多线程与多进程(1)——以操作系统的角度述说线程与进程>一文详细讲述了线程.进程的关系及在操作系统中的表现,这是多线程学习必须了解的基础.本文将接着讲一下Java中多线程程序的 ...

  7. Hive 常用语句(持续更新中)

    1)按包含关键字在指定库中查找表名:show tables in dw '*_fab_*';   2)查看和删除自己hdfs系统所用的空间和文件(与shell命令合用):hive命令行下: --查看仓 ...

  8. stl string 使用(转载)

    出处:http://www.cnblogs.com/lzjsky/archive/2011/01/23/1942508.html 1. 查找字符 std::wstring strData = L&qu ...

  9. C++快速输入输出优化

    在这里存一下我的快速输入输出优化 以及写题模板 这里的是$getchar$优化和$putchar$优化,$fread$和$fwrite$暂时咕咕咕 快速输入 这里$define$了一个$I\_int$ ...

  10. 【Android实验】第一个Android程序与Activity生命周期

    目录 第一个Android程序和Activity生命周期 实验目的 实验要求 实验过程 1. 程序正常启动与关闭 2. 外来电话接入的情况 3. 外来短信接入的情况 4. 程序运行中切换到其他程序(比 ...