Android訪問網(wǎng)絡(luò)的兩種主要方式:
1茬腿、標(biāo)準(zhǔn)Java接口(java.net) ----HttpURLConnection聚至,可以實(shí)現(xiàn)簡單的基于URL請(qǐng)求慧瘤、響應(yīng)功能戴已;
2、Apache接口(org.appache.http)----HttpClient锅减,使用起來更方面更強(qiáng)大糖儡。一般來說,用這種接口怔匣。
下面以一個(gè)安卓項(xiàng)目為例分別介紹這兩個(gè)類的用法:
該項(xiàng)目的主要功能是訪問百度www.baidu.com網(wǎng)址握联,將返回的html內(nèi)容顯示在安卓界面上。
1劫狠、新建布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:id="@+id/click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click" />
<ScrollView
android:layout_below="@+id/click"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</ScrollView>
</RelativeLayout>
這里用到了按鈕和文字拴疤,由于安卓界面大小的原因永部,我將文字部分放置在ScrollView(滾動(dòng)視圖)中独泞,以便用戶查看內(nèi)容。
2苔埋、MainActivity.java
/*在Android上發(fā)送HTTP請(qǐng)求的方式一般有兩種懦砂,HttpURLConnection和HttpClient,現(xiàn)在先學(xué)習(xí)下
HttpURLConnection的用法。
1荞膘、獲取HttpURLConnection的實(shí)例罚随,new 出一個(gè)URL對(duì)象,并傳入目標(biāo)網(wǎng)絡(luò)的地址 調(diào)用一下openConnection()方法即可羽资,如下所示:
URL URL = new URL("http://www.baidu.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
2淘菩、設(shè)置一下HTTP請(qǐng)求所使用的方法。常用的方法主要有兩個(gè)屠升,
(1)GET表示希望從服務(wù)器那里獲取數(shù)據(jù)潮改。
(2)POST則表示提交數(shù)據(jù)給服務(wù)器。寫法如下:
connection.setRequestMethod("GET");
3腹暖、接下來就可以進(jìn)行一些自由的定制了汇在,比如設(shè)置連接超時(shí),讀取超時(shí)的毫秒數(shù)脏答,以及服務(wù)器希望得到的一些消息頭等糕殉。
這部分內(nèi)容根據(jù)自己的實(shí)際情況進(jìn)行編寫,示例如下:
connection.setConnectionTimeout(8000);
connection.setReadTimeout(8000);
4殖告、調(diào)用getInputStream()方法就可以獲取到服務(wù)器返回的輸入流了
阿蝶,剩下的任務(wù)就是對(duì)輸入流進(jìn)行讀取,如下所示:
InputStream in = connection.getInputStream();
5黄绩、最后可以調(diào)用disconnect()方法將這個(gè)HTTP連接關(guān)閉掉赡磅,如下所示:
connection.disconnection();*/
完整代碼:
package com.chen.networktest;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends ActionBarActivity {
public static final int SHOW_RESPONSE = 0;
private Button buttonClick;
private TextView textViewResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonClick = (Button) findViewById(R.id.click);
textViewResult = (TextView) findViewById(R.id.hello);
buttonClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendRequestWithHttpURLConnection();
}
});
}
//實(shí)例化Handler對(duì)象,用于在子線程發(fā)送消息到主線程宝与,并在主線程進(jìn)行消息處理
private Handler handler = new Handler() {
//handleMessage方法運(yùn)行在主線程焚廊,處理子線程發(fā)送回來的數(shù)據(jù)。
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String) msg.obj;
//在這里進(jìn)行UI操作习劫,將結(jié)果顯示到界面上
textViewResult.setText(response);
break;
default:
break;
}
}
};
private void sendRequestWithHttpURLConnection() {
//開啟線程來發(fā)起網(wǎng)絡(luò)請(qǐng)求
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
InputStream in = connection.getInputStream();
//下面對(duì)獲取到的輸入流進(jìn)行讀取
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
//實(shí)例化Message對(duì)象
Message message = new Message();
message.what = SHOW_RESPONSE;
//將服務(wù)器返回的結(jié)果存放到Message中
message.obj = response.toString();
//sendMessage方法運(yùn)行在子線程
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
}
HttpClient的用法:
1咆瘟、獲取HttpClient的實(shí)例,new DefaultHttpClient()這個(gè)實(shí)現(xiàn)類
2诽里、實(shí)例化HttpGet或者HttpPost對(duì)象袒餐,參數(shù)為一個(gè)url
private void sendRequestWithHttpClient() {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.baidu.com");
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//請(qǐng)求和響應(yīng)都成功了
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity, "utf-8");
Message message = new Message();
message.what = SHOW_RESPONSE;
//將服務(wù)器返回的結(jié)果存放到Message中
message.obj = response.toString();
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
注意:記得在AndroidManifest.xml里面添加權(quán)限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>