$《第一行代码:Android》读书笔记——第10章 Android网络编程
WebView webView = (WebView)findViewById(R.id.web_view);
webView.getSettings( ).setJavaScriptEnabled(true); //让webView支持javascript脚本
webView.setWebViewClient(new WebViewClient( ){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url); //根据传入的参数再去加载新的网页
return true; //表示当前WebView可以处理打开新网页的请求,不用借助系统浏览器
}
});
webView.loadUrl("http://www.baidu.com");
3、使用任何网络功能的程序都要申请权限:
<uses-permission android:name="android.permission.INTERNET" />
(二)使用HttpURLConnection访问网络
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
(2)设置HttpURLConnection是GET方法还是POST方法:
connection.setRequestMethod("GET");
(3)对HttpURLConnection进行其他的设置:
connection.setConnectTimeout(8000); //设置连接超时的毫秒数
connection.setReadTimeout(8000); //设置读取超时的毫秒数
(4)用HttpURLConnection对象的getInputStream方法获取服务器的返回输入流InputStream对象:
InputStream in = connection.getInputStream();
(5)对输入流进行读取:
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
(6)用disconnect方法关闭这个HTTP连接:
connection.disconnect();
2、注意:
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://10.0.2.2:8081/get_data.xml");
②POST请求:
HttpPost httpPost = new HttpPost("http://www.baidu.com");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username","admin"));
params.add(new BasicNameValuePair("password","123456"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
httpPost.setEntity(entity);
(3)获取服务器返回值:
HttpResponse httpResponse = httpClient.execute(httpGet);
(4)判断返回状态码,如果等于200就表示请求和响应都成功了:
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity, "utf-8");
... //其他操作
}
3、注意:HttpClient访问网络同样要放在子线程里、申请网络权限。
public interface HttpCallbackListener {
void onFinish(String response); //在服务器成功响应请求时调用
void onError(Exception e); //进行网络操作出错时调用
}
2、创建HttpUtil类:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL; public class HttpUtil {
public static void sendHttpRequest(final String address,final HttpCallbackListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null; try {
URL url = new URL(address);
connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setDoInput(true);
connection.setDoOutput(true); InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line; while ((line = reader.readLine()) != null) {
response.append(line);
} if (listener != null) {
// 回调onFinish方法
listener.onFinish(response.toString());
} } catch (Exception e) {
if (listener != null) {
listener.onError(e);
}
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
}
3、使用时这样使用:
HttpUtil.sendHttpRequest("http://www.baidu.com",new HttpCallBackListener(){
@Override
public void onFinish(String response){
//在这里根据返回内容执行具体的逻辑
} @Override
public void onError(Exception e){
//在这里对异常情况进行处理
}
});
(五)解析XML数据
<apps>
<app>
<id>1</id>
<name>Google Maps</name>
<version>1.0</version>
</app>
<app>
<id>2</id>
<name>Chrome</name>
<version>1.8</version>
</app>
<app>
<id>3</id>
<name>Google Play</name>
<version>3.2</version>
</app>
</apps>
4、用Pull方式解析XML数据:
private void parseXMLWithPull(String xmlData) {
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParse = factory.newPullParser();
xmlPullParse.setInput(new StringReader(xmlData));
int eventType = xmlPullParse.getEventType(); String id = "";
String name = "";
String version = ""; while (eventType != XmlPullParser.END_DOCUMENT) {
String nodeName = xmlPullParse.getName();
switch (eventType) {
// 开始解析某个结点
case XmlPullParser.START_TAG: {
if ("id".equals(nodeName)) {
id = xmlPullParse.nextText();
} else if ("name".equals(nodeName)) {
name = xmlPullParse.nextText();
} else if ("version".equals(nodeName)) {
version = xmlPullParse.nextText();
}
}
break;
// 完成解析某个结点
case XmlPullParser.END_TAG: {
if ("app".equals(nodeName)) {
Log.d("MainActivity", "id is " + id);
Log.d("MainActivity", "name is " + name);
Log.d("MainActivity", "version is " + version);
}
}
break;
default:
break;
} eventType = xmlPullParse.next();
}
} catch (Exception e) {
e.printStackTrace();
}
}
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler; import android.util.Log; public class ContentHandler extends DefaultHandler {
private String nodeName;
private StringBuilder id;
private StringBuilder name;
private StringBuilder version; @Override
public void startDocument() throws SAXException {
id = new StringBuilder();
name = new StringBuilder();
version = new StringBuilder();
} @Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// 记录当前结点名
nodeName = localName;
} @Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// 根据当前结点名判断将内容添加到哪一个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);
}
} @Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// 用trim方法去掉空白字符
if ("app".equals(localName)) {
Log.d("MainActivity", "id is " + id.toString().trim());
Log.d("MainActivity", "name is " + name.toString().trim());
Log.d("MainActivity", "version is " + version.toString().trim()); // 将StringBuilder清空
id.setLength(0);
name.setLength(0);
version.setLength(0);
}
} @Override
public void endDocument() throws SAXException {
}
}
(2)写具体方法:
private void parseXMLWithSAX(String xmlData) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
XMLReader xmlReader = factory.newSAXParser().getXMLReader();
ContentHandler handler = new ContentHandler(); xmlReader.setContentHandler(handler); // 开始执行解析
xmlReader.parse(new InputSource(new StringReader(xmlData)));
} catch (Exception e) {
e.printStackTrace();
}
}
【本章结束】
随机推荐
- size_t ssize_t loff_t 的区别
Ssize_t 与size_t 跟踪linux源码得到以下宏: #ifndef _SIZE_T #define _SIZE_T typedef __kernel_size_t size ...
- typescript 接口的新认识
interface 用于接收服务器的数据. eg: interface mmmmm { x: string, y: number, z: number, select: KnockoutObserva ...
- 图像增强之DDE---基于红外图像的数字图像细节增强DDE
(1)DDE应用背景 (2)DDE算法简介 (3)DDE 实现 (4)DDE 总结和不足 ----------author:pkf -----------------time:2-9 -------- ...
- MFC 资源记录
MFC的RC文件中,定义很多中资源,每种资源具体是如何定义的,资源文件中各种符号都是什么意义? LTEXT "A&xis:",IDC_STATIC,12 ...
- winform 的 checklistbox动态绑定并选中值
绑定的代码:这里绑定的是一个泛型 BLL.PowerBLL powerbll = new BLL.PowerBLL(); checkpower.DataSource = powerbll.GetAll ...
- TelephonyManager&GsmCellLocation类的方法详解
转载:http://blog.163.com/zhangzheming_282/blog/static/117920962011101944356511/ TelephonyManager类 主要提供 ...
- Win API:之GetCurrentThread、GetCurrentThreadId、GetCurrentProcess、GetCurrentProcessId
Win API:之GetCurrentThread.GetCurrentThreadId.GetCurrentProcess.GetCurrentProcessId {返回当前线程的虚拟句柄} Get ...
- python多线程爬虫:亚马逊价格
import re import requests import threading import time from time import ctime,sleep from queue impor ...
- TCP和UDP 协议发送数据包的大小
在进行UDP编程的时候,我们最容易想到的问题就是,一次发送多少bytes好? 当然,这个没有唯一答案,相对于不同的系统,不同的要求,其得到的答案是不一样的,这里仅对像ICQ一类的发送聊天消息的情况作分 ...
- iOS学习笔记(一)——ios搭建开发环境
好久就想试水IOS开发了,由于开发环境限制,一直局限于理论和虚拟机,近来入手了MacBook Pro,也来尝尝鲜,笔者也是现学现总结,如果有不足,请指正. IOS开发必备MAC OS X 另加一部iP ...