第三十讲:URLConnection和HttpClient使用入门

本讲内容: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的内容如下:

01<?xml version="1.0" encoding="utf-8"?>
02<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
03
04<textview android:id="@+id/TextView01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="网络连接测试">
05
06<button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="使用URLConnection访问GoogleWeatherAPI">
07</button>
08
09<button android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="使用HttpClient访问GoogleWeatherAPI">
10</button>
11
12<scrollview android:id="@+id/ScrollView01" android:layout_width="wrap_content" android:layout_height="wrap_content">
13    <textview android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content">
14    </textview>
15</scrollview>
16</textview></linearlayout>

 

3、MainActivity.java的内容如下:

001package android.basic.lesson30;
002
003import java.io.InputStreamReader;
004import java.net.HttpURLConnection;
005import java.net.URL;
006
007import org.apache.http.client.ResponseHandler;
008import org.apache.http.client.methods.HttpGet;
009import org.apache.http.impl.client.BasicResponseHandler;
010import org.apache.http.impl.client.DefaultHttpClient;
011
012import android.app.Activity;
013import android.os.Bundle;
014import android.view.View;
015import android.widget.Button;
016import android.widget.TextView;
017import android.widget.Toast;
018
019public class MainActivity extends Activity {
020
021    TextView tv;
022
023    String googleWeatherUrl1 = "http://www.google.com/ig/api?weather=zhengzhou";
024    String googleWeatherUrl2 = "http://www.google.com/ig/api?hl=zh-cn&weather=zhengzhou";
025
026    /** Called when the activity is first created. */
027    @Override
028    public void onCreate(Bundle savedInstanceState) {
029        super.onCreate(savedInstanceState);
030        setContentView(R.layout.main);
031
032        // 定义UI组件
033        Button b1 = (Button) findViewById(R.id.Button01);
034        Button b2 = (Button) findViewById(R.id.Button02);
035        tv = (TextView) findViewById(R.id.TextView02);
036
037        // 设置按钮单击监听器
038        b1.setOnClickListener(new View.OnClickListener() {
039            @Override
040            public void onClick(View v) {
041                // 使用URLConnection连接GoogleWeatherAPI
042                urlConn();
043            }
044        });
045
046        // 设置按钮单击监听器
047        b2.setOnClickListener(new View.OnClickListener() {
048            @Override
049            public void onClick(View v) {
050                // 使用HttpCient连接GoogleWeatherAPI
051                httpClientConn();
052
053            }
054        });
055
056    }
057
058    // 使用URLConnection连接GoogleWeatherAPI
059    protected void urlConn() {
060
061        try {
062            // URL
063            URL url = new URL(googleWeatherUrl1);
064            // HttpURLConnection
065            HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
066
067            if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
068                Toast.makeText(getApplicationContext(), "连接Google Weather API成功!",
069                        Toast.LENGTH_SHORT).show();
070                // InputStreamReader
071                InputStreamReader isr = new InputStreamReader(httpconn.getInputStream(), "utf-8");
072                int i;
073                String content = "";
074                // read
075                while ((i = isr.read()) != -1) {
076                    content = content + (char) i;
077                }
078                isr.close();
079                //设置TextView
080                tv.setText(content);
081            }
082            //disconnect
083            httpconn.disconnect();
084
085        } catch (Exception e) {
086            Toast.makeText(getApplicationContext(), "连接Google Weather API失败", Toast.LENGTH_SHORT)
087                    .show();
088            e.printStackTrace();
089        }
090    }
091
092    // 使用HttpCient连接GoogleWeatherAPI
093    protected void httpClientConn() {
094        //DefaultHttpClient
095        DefaultHttpClient httpclient = new DefaultHttpClient();
096        //HttpGet
097        HttpGet httpget = new HttpGet(googleWeatherUrl2);
098        //ResponseHandler
099        ResponseHandler<string> responseHandler = new BasicResponseHandler();
100
101        try {
102            String content = httpclient.execute(httpget, responseHandler);
103            Toast.makeText(getApplicationContext(), "连接Google Weather API成功!",
104                    Toast.LENGTH_SHORT).show();
105            //设置TextView
106            tv.setText(content);
107        } catch (Exception e) {
108            Toast.makeText(getApplicationContext(), "连接Google Weather API失败", Toast.LENGTH_SHORT)
109            .show();
110            e.printStackTrace();
111        }
112        httpclient.getConnectionManager().shutdown();
113    }
114}</string>

 

4、最后别忘了在AndroidManifest.xml中加入访问网络的权限,<uses-permission android:name="android.permission.INTERNET"></uses-permission>

5、运行程序查看结果:

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

 

 

image 
按第二个按钮的效果,返回的数据结果显示在了TextView里, 所不同的是显示的是中文。

好了,本讲先到这里。

转自 http://android.yaohuiji.com/archives/932

posted on 2011-11-02 11:16  moss  阅读(168)  评论(0)    收藏  举报

导航