1791 本講內(nèi)容:URLConnection和HttpClient使用入門(mén) 在Android中除了使用WebView控件訪問(wèn)網(wǎng)絡(luò)以外,還有用代碼方式訪問(wèn)網(wǎng)絡(luò)的方法,代碼方式有時(shí)候會(huì)顯得更加靈活。本講會(huì)介紹使用URLConnection對(duì)象和HttpClient組件訪問(wèn)網(wǎng)絡(luò)的方法。而這兩種方法和Java Web開(kāi)發(fā)中的使用方式幾乎沒(méi)有區(qū)別,而Web開(kāi)發(fā)的相關(guān)資料比比皆是,因此有興趣的同學(xué)學(xué)完本講之后可以專(zhuān)門(mén)去研究一下HttpClient4.0的內(nèi)容,以求更深入的學(xué)習(xí)。 一、分別使用URLConnection和HttpClient訪問(wèn)Google天氣服務(wù)的例子 這個(gè)例子的的目的就是從Google哪里獲取鄭州的天氣預(yù)報(bào)信息,并顯示在TextView中,本講只會(huì)把返回的XML數(shù)據(jù)顯示出來(lái),下一講我們學(xué)XML解析的時(shí)候再把這個(gè)天氣預(yù)報(bào)做成圖文并茂的形式,所以大家先暫時(shí)忍耐一下丑陋的界面。 1、新建一個(gè)項(xiàng)目 Lesson30_HttpClient ,主Activity的文件名是 MainActivity.java 2、res/layout/main.xml的內(nèi)容如下: - <?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
<textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/TextView01" android:text="網(wǎng)絡(luò)連接測(cè)試">
<button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/Button01" android:text="使用URLConnection訪問(wèn)GoogleWeatherAPI">
</button>
<button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/Button02" android:text="使用HttpClient訪問(wèn)GoogleWeatherAPI">
</button>
<scrollview android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ScrollView01">
<textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/TextView02">
</textview>
</scrollview>
</textview></linearlayout>
復(fù)制代碼 3、MainActivity.java的內(nèi)容如下: - package android.basic.lesson30;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView tv;
String googleWeatherUrl1 = "http://www.google.com/ig/api?weather=zhengzhou";
String googleWeatherUrl2 = "http://www.google.com/ig/api?hl=zh-cn&weather=zhengzhou";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 定義UI組件
Button b1 = (Button) findViewById(R.id.Button01);
Button b2 = (Button) findViewById(R.id.Button02);
tv = (TextView) findViewById(R.id.TextView02);
// 設(shè)置按鈕單擊監(jiān)聽(tīng)器
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 使用URLConnection連接GoogleWeatherAPI
urlConn();
}
});
// 設(shè)置按鈕單擊監(jiān)聽(tīng)器
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 使用HttpCient連接GoogleWeatherAPI
httpClientConn();
}
});
}
// 使用URLConnection連接GoogleWeatherAPI
protected void urlConn() {
try {
// URL
URL url = new URL(googleWeatherUrl1);
// HttpURLConnection
HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
Toast.makeText(getApplicationContext(), "連接Google Weather API成功!",
Toast.LENGTH_SHORT).show();
// InputStreamReader
InputStreamReader isr = new InputStreamReader(httpconn.getInputStream(), "utf-8");
int i;
String content = "";
// read
while ((i = isr.read()) != -1) {
content = content + (char) i;
}
isr.close();
//設(shè)置TextView
tv.setText(content);
}
//disconnect
httpconn.disconnect();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "連接Google Weather API失敗", Toast.LENGTH_SHORT)
.show();
e.printStackTrace();
}
}
// 使用HttpCient連接GoogleWeatherAPI
protected void httpClientConn() {
//DefaultHttpClient
DefaultHttpClient httpclient = new DefaultHttpClient();
//HttpGet
HttpGet httpget = new HttpGet(googleWeatherUrl2);
//ResponseHandler
ResponseHandler<string> responseHandler = new BasicResponseHandler();
try {
String content = httpclient.execute(httpget, responseHandler);
Toast.makeText(getApplicationContext(), "連接Google Weather API成功!",
Toast.LENGTH_SHORT).show();
//設(shè)置TextView
tv.setText(content);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "連接Google Weather API失敗", Toast.LENGTH_SHORT)
.show();
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
}
}</string>
復(fù)制代碼 4、最后別忘了在AndroidManifest.xml中加入訪問(wèn)網(wǎng)絡(luò)的權(quán)限,<uses-permission android:name="android.permission.INTERNET"></uses-permission>5、運(yùn)行程序查看結(jié)果:
按第一個(gè)按鈕的效果,返回的數(shù)據(jù)結(jié)果顯示在了TextView里。
按第二個(gè)按鈕的效果,返回的數(shù)據(jù)結(jié)果顯示在了TextView里, 所不同的是顯示的是中文。好了,本講先到這里。
|