橘子味的心
标题:8.3 HttpURLConnection访问互联网资源

为了可以通过 AVD 调试网络访问应用程序,首先在本地计算机上架设网络服务器端。使用 Tomcat 做服务器,在其 webapps 目录下建立 android 目录,并在该目录下建立 message.jsp 文件。
  1. <HTTP>
  2. <HEAD>
  3. <TITLE>HTTP-MESSAGE</TITLE>
  4. </HEAD>
  5. <BODY>
  6. <%
  7. OUT.PRINTln("<H1>Http-Message<BR>Android:Hello World</H>");
  8. %>
  9. </BODY>
  10. </HTML>
由于本地计算机在网络上的 IP 为 175.168.35.198,因此 message.jsp 的网络 URL 为 http://175.168.35.198:8080/android/message.jsp。将该地址输入 IE 地址栏打开,其运行效果如图 1 所示。

message.jsp的运行效果
图 1  message.jsp 的运行效果
这样,我们就有了可以通过 AVD 来访问的网络上的资源。

使用 java.net.URLConnection 访问 URL 指定的网络资源的基本过程的代码如下:
  1. URL url=new URL("ftp://mirror.csclub.uwaterloo.ca/index.html");//建立URL
  2. URLConnection urlConnection=url.openConnection();//打开连接
  3. InputStream in=new BufferedInputStream(
  4. urlConnection. getlnputStream());//从连接建立输入流
  5. try {
  6. readstream (in); //读取数据操作
  7. }finally{
  8. in.close();
  9. }
  10. }
URLConnection 内建对多种网络协议的支持,如 HTTP/HTTPS、File、FTP 等。

在创建连接之前,可以对连接的一些属性进行设置,如下表所示。

URLConnection属性
属性名称 属性描述
setReadTimeout(3000) 设置读取数据的超时时间为 3 秒钟
setUseCaches(false) 设置当前连接是否允许使用缓存
setDoOutput(true) 设置当前连接是否允许建立输出流
setDoInput(true) 设置当前连接是否允许建立输入流

HttpURLConnection 继承于 URLConnection 类,二者都是抽象类,所以无法直接实例化,其对象主要通过 URL 的 openConnection 方法获得。

URLConnection 可以直接转换成 HttpURLConnection,以便于使用一些 HTTP 连接特定的方法,如 getResponseMessage()、setRequestMethod() 等。

使用 HttpURLConnection 访问网络资源的基本过程的代码如下:
  1. URL url=new URL("http://www.android.com/");
  2. HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
  3. try {
  4. InputStream in=new BufferedInputStream(urlConnection.getInputStream());
  5. readstream(in);
  6. }finally{
  7. urlConnection.disconnect();
  8. }
需要注意的是,使用 openConnection 方法所创建的 URLConnection 或者 HttpURLConnection 实例不具有重用性,每次调用 openConnection 方法都将创建一个新的实例。

实例 URLDemo 中演示了使用 URL 访问指定资源的过程,运行效果如图 2 所示。
URLDemo的运行效果
图 2  URLDemo 的运行效果

实例 URLDemo 中 main.xml 的代码如下:
  1. <?xml version="1.0” encoding="utf-8"?>
  2.  
  3. <LinearLayout
  4. xmlns:android="http://schemas.android.com/apk/res/android"
  5. android:orientation="vertical"
  6. android:layout_width="fill_parent"
  7. android:layout_height="fill_parent">
  8.  
  9. <Button
  10. android:id="@+id/Button_HTTP"
  11. android:layout_width="fill_parent"
  12. android:layout_height="wrap_content"
  13. android:text="@string/button_name01"/>
  14.  
  15. <TextView
  16. android:id="@+id/TextView_HTTP"
  17. android:layout_width="fill_parent"
  18. android:layout_height="wrap_content"/>
  19.  
  20. </LinearLayout>
实例 URLDemo 中 AndroidManifest.xml 的代码如下:
  1. <?xml version="l.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.android.activity"
  4. android:versionCode="1"
  5. android:versionName="1.0">
  6.  
  7. <uses-sdk android:minSdkVersion="4" />
  8.  
  9. <uses-permission android:name="android.permission.INTERNET" />
  10.  
  11. <application android:icon="@drawable/ic_launcher"
  12. android:label="@string/app_name">
  13. <activity android:name=".MainActivity"
  14. android:label="@string/app_name">
  15.  
  16. <intent-filter>
  17. <action android:name="android.intent.action.MAIN" />
  18. <category android:name="android.intent.category.LAUNCHER" />
  19. </intent-filter>
  20.  
  21. </activity>
  22. </application>
  23. </manifest>
实例 URLDemo 中 MainActivity.java 的具体实现代码如下:
  1. package introdction.android.URLDemo;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputstreamReader;
  6. import java.net.HttpURLConnection;
  7. import java.net.MalformedURLException;
  8. import java.net.URL;
  9. import com.android.activity.R;
  10. import android.app.Activity;
  11. import android.os.Bundle;
  12. import android.view.View;
  13. import android.view.View.OnClickListener;
  14. import android.widget.Button;
  15. import android.widget.TextView;
  16.  
  17. public class MainActivity extends Activity {
  18. /** Called when the activity is first created. */
  19.  
  20. private TextView textView_HTTP;
  21.  
  22. @Override
  23. public void onCreate (Bundle savedInstanceState) {
  24. super.onCreate (savedInstanceState);
  25. setContentView (R.layout.main);
  26. textView_HTTP= (TextView) findViewById (R.id.TextView_HTTP);
  27. Button button_http= (Button) findViewById (R.id.Button_HTTP) ;
  28.  
  29. button_http. setOnClickListener (new OnClickListener () {
  30. //给button_http按钮设置监听器
  31. public void onClick (View v) {//事件处理
  32.  
  33. String httpUrl="http://175.168.35.198:8080/android/message.jsp";
  34. String resultData="";//定义一个resultData用于存储获得的数据
  35. URL url=null; //定义URL对象
  36. try {
  37. url=new URL (httpUrl); //构造一个URL对象时需要使用异常处理
  38. } catch (MalformedURLException e) {
  39. System.out.println (e.getMessage ());//打印出异常信息
  40. }
  41.  
  42. if (url !=null) {//如果URL不为空时
  43. try{
  44. //有关网络操作时,需要使用异常处理
  45. HttpURLConnection urlConn= (HttpURLConnection)url.openConnection (); //使用HttpURLConnection打开连接
  46.  
  47. InputStreamReader in=new InputStreamReader (urlConn.getInputStream());//得到读取的内容
  48. BufferedReader buffer=new BufferedReader (in);//为输出创建BufferedReader
  49. String inputLine=null;
  50. while (((inputLine=buffer.readLine()) !=null)) {
  51. // 读取获得的数据
  52. resultData+=inputLine+"\n"; // 加上"\n"实现换行
  53. }
  54.  
  55. in.close();//关闭InputStreamReader
  56. urlConn.disconnect(); //关闭HTTP连接
  57. if (resultData !=null) {//如果获取到的数据不为空
  58. textView_HTTP.setText(resultData) ;
  59. } else {
  60. textView_HTTP.setText("Sorry,the content is null");//获取到的数据为空时显示
  61. }
  62.  
  63. } catch (IOException e) {
  64. textView_HTTP.setText (e.getMessage());
  65. //出现异常时,打印异常信息
  66. }
  67.  
  68. } else {
  69. textView_HTTP.setText ("url is null"); //当url为空时输出
  70. }
  71. }
  72.  
  73. }) ;
  74.  
  75. }
以上代码中,

String httpUrl = "http://175.168.35.198:8080/android/message.jsp ";

指定了要访问的网络资源的地址,测试时改成自己本机的IP地址即可。