$《第一行代码: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();
}
}
【本章结束】
随机推荐
- Unity3D 移动开发代码优化
1. 尽量避免每帧处理 比方: function Update() { DoSomeThing(); } 可改为每5帧处理一次: function Update() { if(Time.frameCo ...
- html 常用
1. var canvas = document.getElementById("tutorial"); var ctx = canvas.getContext("2d& ...
- tomcat本身的lib目录都有哪些jar包
1.tomcat下的lib目录,自己带有的jar包有:servlet.jar,tomcat-jdbc.jar,tomncat-dbcp.jar,jsp.jar等 2.tomcat下的lib目录,自己带 ...
- 学习boost::asio一些小例子
# #include <boost/asio.hpp> #include <boost/thread.hpp> #include <iostream> void h ...
- 合并子目录(hash)
题目2 : 合并子目录 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi的电脑的文件系统中一共有N个文件,例如: /hihocoder/offer22/soluti ...
- 使用MyBatis_Generator工具jar包自动化生成Dto、Dao、Mapping 文件
由于MyBatis属于一种半自动的ORM框架,所以主要的工作将是书写Mapping映射文件,但是由于手写映射文件很容易出错,所以查资料发现有现成的工具可以自动生成底层模型类.Dao接口类甚至Mappi ...
- JS HTML DOM---Document对象
Document 对象 当浏览器载入 HTML 文档, 它就会成为 document 对象. document 对象是HTML文档的根节点与所有其他节点(元素节点,文本节点,属性节点, 注释节点). ...
- 搭建Spring所需的各类jar包汇总详解
Spring jar包官网下载地址:http://repo.spring.io/release/org/springframework/spring/ Spring jar包的描述:针对3.2.2以上 ...
- Webstorm如何设置背景色为护眼色(豆绿色)
本文主要讲webstorm如何设置背景色. 1.打开idea Settings 选择 Editor——Color Scheme——General 注意:如果是Mac,在webstorm界面按键:“co ...
- Android系统移植与调试之------->如何修改Android设备状态条上音量加减键在横竖屏切换的时候的显示于隐藏
这两天由于一个客户的要求,将MID竖屏时候的状态条上的音量键去掉.所以尝试修改了一下,成功了,分享一下经验. 先看一下修改后的效果图,如下所示 . 横屏的时候:有音量加减键 竖屏的时候:音量加减键被去 ...