2010104第一行代碼第十章網(wǎng)絡(luò)

一、WebView

view=(WebView) findViewById(R.id.webView1);

view.setWebViewClient(new WebViewClient(){

@Override

public boolean shouldOverrideUrlLoading(WebView view, String url) {

// TODO Auto-generated method stub

view.loadUrl(url); ??//根據(jù)傳入的參數(shù)再去加載新的網(wǎng)頁(yè)

return true; ????????//表示當(dāng)前WebView可以處理打開(kāi)新網(wǎng)頁(yè)的請(qǐng)求,不用借助系統(tǒng)瀏覽器

}

});

view.loadUrl("http://www.baidu.com");

訪問(wèn)網(wǎng)絡(luò)是需要聲明權(quán)限的:

二、使用HTTP協(xié)議訪問(wèn)網(wǎng)絡(luò)

在Android中發(fā)送http請(qǐng)求有兩種方法:HttpURLConnection和HttpClient。

1、使用HttpURLConnection

首先,獲取訪問(wèn)地址的URL;

然后,利用該url實(shí)例的openConnection()方法獲取HttpURLConnection實(shí)例;

之后,利用HttpURLConnection實(shí)例,可以設(shè)置HTTP請(qǐng)求所使用的方法,主要有兩種,GET和POST,分別是請(qǐng)求數(shù)據(jù)和提交數(shù)據(jù);

之后,可以進(jìn)行一些自由的設(shè)置,比如設(shè)置連接超時(shí)時(shí)間、請(qǐng)求超時(shí)時(shí)間等;

最后,調(diào)用getInputStream()方法即可獲得服務(wù)器傳輸過(guò)來(lái)的輸入流了。可以對(duì)該輸入流進(jìn)行讀取。

讀取完之后,需要關(guān)閉HTTP連接,調(diào)用disconnect()方法。

當(dāng)然,也需要在AndroidManifest.xml中注冊(cè)。

url = new URL("http://www.baidu.com");

HttpURLConnection connection=(HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");

connection.setReadTimeout(8000);

connection.setConnectTimeout(8000);

InputStream inputStream=connection.getInputStream();

主程序如下:

public class MainActivity extends Activity {

Button send;

TextView textView;

public static final int REQUEST=0;

private Handler handler=new Handler()

{

public void handleMessage(Message msg) {

super.handleMessage(msg);

switch (msg.what) {

case REQUEST:

String responce=msg.obj.toString();

textView.setText(responce);

break;

default:

break;

}

}

};

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

send=(Button) findViewById(R.id.send);

textView=(TextView) findViewById(R.id.text);

send.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

SendRequest();

}

});

}

public void SendRequest()

{

//打開(kāi)一個(gè)子線程用于請(qǐng)求網(wǎng)頁(yè)

new Thread(new Runnable() {

public void run() {

HttpURLConnection connection=null;

BufferedReader reader;

URL url;

try {

url = new URL("http://www.baidu.com");

connection=(HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");

connection.setReadTimeout(8000);

connection.setConnectTimeout(8000);

InputStream inputStream=connection.getInputStream();

InputStreamReader inputStreamReader=new InputStreamReader(inputStream);

reader=new BufferedReader(inputStreamReader);

StringBuilder builder=new StringBuilder();

String line="";

while((line=reader.readLine())!=null)

{

builder.append(line);

}

Message ?message=new Message();

message.what=REQUEST;

message.obj=builder;

handler.sendMessage(message);

} catch (Exception e) {

e.printStackTrace();

}

finally

{

if(connection!=null)connection.disconnect();

}

}

}).start();

}

…….

}

向服務(wù)器提交數(shù)據(jù):

首先,將HTTP請(qǐng)求方法改為POST;

然后,打開(kāi)輸出流。

之后,將數(shù)據(jù)以鍵值對(duì)方式輸出,數(shù)據(jù)之間用&隔開(kāi)。

connection.setRequestMethod("POST");

OutputStream outputStream=connection.getOutputStream();

DataOutputStream dataOutputStream=new DataOutputStream(outputStream);

dataOutputStream.writeBytes("username=hujun&password=123");

2、使用HttpClient

HttpClient是Apache提供的網(wǎng)絡(luò)訪問(wèn)接口。

首先,因?yàn)槭墙涌冢圆荒軐?shí)例化,通常創(chuàng)建一個(gè)DefaultHttpClient的實(shí)例:

HttpClient httpClient = new DefaultHttpClient();

(1)GET請(qǐng)求

創(chuàng)建HttpGet對(duì)象,傳入目標(biāo)網(wǎng)絡(luò)地址,然后調(diào)用HttpClient的excute()方法。

HttpGet httpGet = new HttpGet(“http://www.baidu.com”);

httpClient.excute(httpGet);

(2)POST請(qǐng)求

首先,創(chuàng)建一個(gè)HttpPost對(duì)象,傳入網(wǎng)絡(luò)目標(biāo)地址;

之后,用NameValuePair集合存放數(shù)據(jù);

之后,設(shè)置數(shù)據(jù)存放格式為utf-8,利用UrlEncodeFormEntity轉(zhuǎn)碼;

之后,將轉(zhuǎn)碼后的entity放入HttpPost對(duì)象;setEntity();

最后,調(diào)用httpClient的excute()方法即可。

//創(chuàng)建HttpPost對(duì)象

HttpPost httpPost = new HttpPost(“http://www.baidu.com”);

//放入數(shù)據(jù)

List params = new ArrayList();

params.add(new BasicNameValuePair(“username”,”hujun” ));

params.add(new BasicNameValuePair(“password”,”123” ));

//轉(zhuǎn)碼

UrlEncodeFormEntity entity = new UrlEncodeFormEntity(params,”utf-8”);

httpPost.setEntity(entity);

//執(zhí)行

httpClient.excute(httpPost);

(3)服務(wù)器返回結(jié)果

執(zhí)行excute()之后,服務(wù)器會(huì)返回一個(gè)HttpResponse對(duì)象,該對(duì)象中包含所有的返回結(jié)果。

首先,取出服務(wù)器返回的狀態(tài)碼,如果狀態(tài)碼為200,說(shuō)明響應(yīng)成功了。

HttpResponse httpResponse = httpClient.excute(httpGet/httpPost);

if(httpResponse.getStatusLine().getStatueCode()==200)

{

//執(zhí)行返回成功之后的代碼

}

之后,取出返回結(jié)果。先用getEntity()獲取HttpEntity實(shí)例,然后用EntityUtils.toString(entity,”utf-8”)將entity轉(zhuǎn)換為字符串。

public void SendClient()

{

new Thread(new Runnable() {

public void run() {

HttpClient httpClient = new DefaultHttpClient();

HttpPost httpPost = new HttpPost("http://www.baidu.com");

List params=new ArrayList();

params.add(new BasicNameValuePair("username", "hujun"));

params.add(new BasicNameValuePair("password", "123"));

try {

UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(params,"utf-8");

httpPost.setEntity(encodedFormEntity);

HttpResponse httpResponse = httpClient.execute(httpPost);

if(httpResponse.getStatusLine().getStatusCode()==200)

{

HttpEntity entity = httpResponse.getEntity();

String response = EntityUtils.toString(entity, "utf-8").toString();

Message message=new Message();

message.what=RESPONSE;

message.obj=response;

handler.sendMessage(message);

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}).start();

}

三、解析XML格式數(shù)據(jù)

首先,需要建立一個(gè)xml文件用于解析。在www文件夾里建立get_data.xml

1

Google Maps

1.0

2

Chrome

2.1

3

Google Play

2.3

然后,利用Android程序去解析這段xml代碼。

1、Pull解析方式

public void parseXMLwithPull(String response)

{

try {

XmlPullParserFactory factory=XmlPullParserFactory.newInstance();

XmlPullParser parser = factory.newPullParser();

parser.setInput(new StringReader(response));

int enventType=parser.getEventType();

while(enventType!=XmlPullParser.END_DOCUMENT)

{

String nodeName=parser.getName();

String id="";

String name="";

String version="";

switch (enventType) {

case XmlPullParser.START_TAG:

if("id".equals(nodeName))

{

id=parser.nextText();

}

else if("name".equals(nodeName))

{

name=parser.nextText();

}

else if("version".equals(nodeName))

{

version=parser.nextText();

}

break;

case XmlPullParser.END_TAG:

if("app".equals(nodeName))

{

Log.i("main", "id= "+id);

Log.i("main", "name= "+name);

Log.i("main", "version= "+version);

}

break;

default:

break;

}

enventType=parser.next();

}

} catch (Exception e) {

e.printStackTrace();

}

}

2SAX解析方式

需要構(gòu)建一個(gè)自己的ContentHandler類去解析XML

public class ContentHandler extends DefaultHandler {

private StringBuilder id;

private StringBuilder name;

private StringBuilder version;

private String nodeName;

public void startDocument() throws SAXException {

super.startDocument();

id = new StringBuilder();

name = new StringBuilder();

version = new StringBuilder();

}

public void startElement(String uri, String localName, String qName,

Attributes attributes) throws SAXException {

super.startElement(uri, localName, qName, attributes);

//記錄當(dāng)前節(jié)點(diǎn)名

nodeName = localName;

}

public void characters(char[] ch, int start, int length)

throws SAXException {

super.characters(ch, start, length);

//根據(jù)當(dāng)前節(jié)點(diǎn)名,判斷將內(nèi)容放入哪個(gè)StringBuilder中

if("id".equals(nodeName))id.append(ch, start, length);

else if("name".equals(nodeName))name.append(ch, start, length);

else if("version".equals(nodeName))version.append(ch, start, length);

}

public void endElement(String uri, String localName, String qName)

throws SAXException {

super.endElement(uri, localName, qName);

if("app".equals(nodeName))

{

Log.i("ContentHandler", "id is "+id.toString().trim());

Log.i("ContentHandler", "name is "+name.toString().trim());

Log.i("ContentHandler", "version is "+version.toString().trim());

//最后需要將StringBuilder清空

id.setLength(0);

name.setLength(0);

version.setLength(0);

}

}

public void endDocument() throws SAXException {

super.endDocument();

}

}

在MainActivity.java中:

public void parseXMLWithSAX(String response)

{

try {

SAXParserFactory factory=SAXParserFactory.newInstance();

XMLReader xmlReader=factory.newSAXParser().getXMLReader();

ContentHandler handler=new ContentHandler();

xmlReader.setContentHandler(handler);

xmlReader.parse(new InputSource(new StringReader(response)));

} catch (Exception e) {

e.printStackTrace();

}

}

、解析JSON格式數(shù)據(jù)

相比XML,JSON優(yōu)勢(shì)在于體積更小,在網(wǎng)絡(luò)上傳輸更省流量。但缺點(diǎn)在于語(yǔ)義性較差,不如XML直觀。

編輯get_data.json文件:

[{"id":"5","name":"hujun","version":"4.4"},

{"id":"6","name":"hujun6","version":"6.6"},

{"id":"7","name":"hujun7","version":"7.7"}]

解析JSON數(shù)據(jù)有很多方法,比如官方提供的JSONObject,也可以使用Google的開(kāi)源庫(kù)GSON。

1JSONObject

public void parseJSONWithJSONObject(String response)

{

try {

JSONArray jsonArray=new JSONArray(response);

for (int i = 0; i < jsonArray.length(); i++) {

JSONObject jsonObject=jsonArray.getJSONObject(i);

String id=jsonObject.getString("id");

String name=jsonObject.getString("name");

String version=jsonObject.getString("version");

Log.i("main", "id= "+id);

Log.i("main", "name= "+name);

Log.i("main", "version= "+version);

}

} catch (Exception e) {

e.printStackTrace();

}

}

private static final String JSON =

"wjr({\"id\":\"35\",\"list\":{\"wjr1\":{\"dengji\":\"2\",\"diming\":\"北京市\(zhòng)",\"daima\":\"110000000000\",\"zidi\":2},\"wjr2\":{\"dengji\":\"2\",\"diming\":\"天津市\(zhòng)",\"daima\":\"120000000000\",\"zidi\":2}}})";

String response=JSON;

response=response.substring(4);

JSONObject province=new JSONObject(response);

JSONObject list=province.getJSONObject("list");

for (int i = 1; i < list.length()+1; i++) {

Log.i("main", list.getJSONObject("wjr"+i).getString("diming"));

Log.i("main", list.getJSONObject("wjr"+i).getString("daima"));

}

2GSON

首先需要一個(gè)Gsonjar包,放在lib中。

GSON可以將一段JSON格式的數(shù)據(jù),自動(dòng)映射為一個(gè)對(duì)象。

比如一段JSON格式數(shù)據(jù)如下:

{"id":"5","name":"hujun","version":"4.4"}

利用GSON可以將上面的JSON格式直接映射為一個(gè)對(duì)象。fromJson()接收兩個(gè)參數(shù):JSON數(shù)據(jù)和需要映射的類。

Gson gson = new Gson();

Person person = gson.fromJson(jsonData,Person.class);

如果需要解析一段JSON數(shù)組,需要用TypeToken將期望解析的數(shù)據(jù)傳入到fromJson()中。

網(wǎng)絡(luò)編程最佳實(shí)踐——java的回調(diào)機(jī)制

將通用的網(wǎng)絡(luò)操作提取到一個(gè)通用的類里,并提供一個(gè)靜態(tài)方法。

但網(wǎng)絡(luò)操作是耗時(shí)操作,因此需要將其放在一個(gè)子線程中進(jìn)行。

由于在子線程中進(jìn)行,在主程序中調(diào)用這個(gè)網(wǎng)絡(luò)操作類時(shí),服務(wù)器還沒(méi)有來(lái)得及響應(yīng),這個(gè)方法就結(jié)束了,根本來(lái)不及返回?cái)?shù)據(jù)。

因此,需要利用java的回調(diào)機(jī)制。

java的回調(diào)機(jī)制:

(1)首先,需要定義一個(gè)接口;

public interface HttpCallBackListner {

void onFinish(String response);

void onError(Exception e);

}

onFinish()方法表示當(dāng)服務(wù)器成功響應(yīng)請(qǐng)求時(shí)調(diào)用,參數(shù)是服務(wù)器的響應(yīng)。

onError()表示網(wǎng)絡(luò)出現(xiàn)錯(cuò)誤時(shí)調(diào)用,參數(shù)是錯(cuò)誤信息。

(2)然后,將接口以參數(shù)形式,放到網(wǎng)絡(luò)操作的通用類中;

public class HttpUtil {

public static void sendHttpRequest(final String address,final HttpCallBackListner listner)

{

new Thread(new Runnable() {

HttpURLConnection connection=null;

public void run() {

try {

URL url = new URL(address);

connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");

connection.setReadTimeout(8000);

connection.setConnectTimeout(8000);

connection.setDoInput(true);

connection.setDoOutput(true);

InputStream inputStream=connection.getInputStream();

InputStreamReader inputStreamReader=new InputStreamReader(inputStream);

BufferedReader bufferedReader=new BufferedReader(inputStreamReader);

StringBuilder builder=new StringBuilder();

String line="";

while((line=bufferedReader.readLine())!=null)

{

builder.append(line);

}

//讀取服務(wù)器響應(yīng)數(shù)據(jù)成功,則調(diào)用onFinish()方法

if(listner!=null)

{

listner.onFinish(builder.toString());

}

} catch (Exception e) {

//網(wǎng)絡(luò)服務(wù)發(fā)送錯(cuò)誤,調(diào)用onError()方法

if(listner!=null)

{

listner.onError(e);

}

}

finally

{

if(connection!=null)connection.disconnect();

}

}

}).start();

}

}

(3)最后,在調(diào)用sendHttpRequest()方法出,重寫(xiě)HttpCallBackListener接口中的方法。

HttpUtil.sendHttpRequest("http://www.baidu.com", new HttpCallBackListner() {

public void onFinish(String response) {

//在這里處理服務(wù)器返回的結(jié)果

}

public void onError(Exception e) {

//在這里處理網(wǎng)絡(luò)出錯(cuò)

}

});

這樣就可以利用回調(diào)機(jī)制,將響應(yīng)數(shù)據(jù)成功的返回給調(diào)用方了。需要注意,onFinish()和onError()方法都是在子線程中運(yùn)行的,因此不能在其中執(zhí)行UI操作,需要用Handler的sendMessage異步處理機(jī)制。

?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,923評(píng)論 18 139
  • apache下的httpclient工具可大大簡(jiǎn)化開(kāi)發(fā)過(guò)程中的點(diǎn)對(duì)點(diǎn)通信,本人將以微信多媒體接口為例,展示http...
    劃破的天空閱讀 5,342評(píng)論 0 32
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類相關(guān)的語(yǔ)法,內(nèi)部類的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚(yú)_t_閱讀 31,765評(píng)論 18 399
  • 1、不安全的隨機(jī)數(shù)生成,在CSRF TOKEN生成、password reset token生成等,會(huì)造成toke...
    nightmare丿閱讀 3,750評(píng)論 0 1
  • Wamp localhost/127.0.0.1 步驟 服務(wù)器工具:http://www.php100.com/h...
    Stago閱讀 153評(píng)論 0 0