第一行代码读书笔记
WebView
- 在应用程序里嵌入一个浏览器
WebView webView = (WebView) findViewById(R.id.web_view);
// 设置浏览器属性
webView.getSettings().setJavaScriptEnabled(true);
// 当需要从一个网页跳转到另一个网页时,目标网页仍在当前WebView中显示
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://www.baidu.com");
- 权限声明
<uses-permission android:name="android:permission:INTERNET" />
使用HTTP协议访问网络
HttpURLConnection
// 获取HttpURLConnection实例
URL url = new URL("http://www.baidu.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置HTTP请求所使用的方法
// GET/POST
connection.setRequestMethod("GET");
//自定义设置
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
// 获取服务器返回的输入流
InputStream in = connection.getInputStream();
// 关闭HTTP连接
connection.disconnect();
- 开启子线程发起HTTP请求,用
runOnUiThread()
方法将线程切换到主线程进行UI操作 POST
:在获取输入流之前把要提交的数据写出,每条数据都要以键对值的形式存在,数据与数据之间用&
符号隔开connection.setRequestMethod("POST"); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.writeByte("username=admin&password=123456");
OkHttp
- 项目地址:
https://github.com/square/okhttp
- 添加依赖
'com.sqareup.okhttp3:okhttp:3.4.1'
- GET
// 创建OkHttpClient OkHttpClient client = new OkHttpClient(); // 创建空的Request对象 // Request request = new Request.Builder().build(); // 在最终的build()之前连缀其他方法丰富Request对象 Request request = new Request.Builder().url("www.baidu.com").build(); // 创建Call对象,并调用它的execute()放松请求并获取服务器返回的数据 // Response对象就是服务器返回的数据 Response response = client.newCall(request).execute(); // 获取返回的具体内容 String responseData = response.body().string();
- POST
// 创建OkHttpClient OkHttpClient client = new OkHttpClient(); // 构建一个RequestBody对象存放待提交的数据 RequestBody requestBody = new FormBody.Builder .add("username", "admin") .add("password", "123456") .build() // 在Request.Builder中调用post()方法,并将RequestBody对象传入 Request request = new Request.Builder() .url("www.baidu.com") .post(requestBody) .build(); // 创建Call对象,并调用它的execute()放松请求并获取服务器返回的数据 // Response对象就是服务器返回的数据 Response response = client.newCall(request).execute();
解析XML格式数据
Pull解析
private void parseXMLWithPull(String xmlData) {
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser = factory.newPullParser();
xmlPullParser.setInput(new StringReader(xmlData));
int eventType = xmlPullParser.getEventType();
String id = "";
String name = "";
String version = "";
while (eventType != XmlPullParser.END_DOCUMENT) {
String nodeName = xmlPullParser.getName();
switch (eventType) {
case XmlPullParser.START_TAG: {
if ("id".equals(nodeName)) {
id = xmlPuallParser.nextText();
} else if ("name".equals(nodeName)) {
name = xmlPuallParser.nextText();
} else if ("version".equals(nodeName)) {
version = xmlPuallParser.nextText();
}
break;
}
case XmlPuallParser,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 = xmlPuallParser.next();
}
} catch (Exception e) {
e.printStackTrace();
}
}
SAX解析
- 用法比Pull解析复杂一些,语义方面更清楚
public class MyHandler extends DefaultHandler {
private String nodeName;
private StringBuilderid;
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 {
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 {
if ("app".equals(nodeName)) {
Log.d("ContentHanlder", "id is " + id.toString().trim());
Log.d("ContentHanlder", "name is " + name.toString().trim());
Log.d("ContentHanlder", "version is " + version.toString().trim());
id.setLength(0);
name.setLength(0);
version.setLength(0);
}
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
}
startDocument()
startElement()
characters()
endElement()
endDocument()
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();
}
}
DOM解析
- 略
解析JSON格式数据
- JSONObject, GSON, Jackson, FastJSON etc.
JSONObject
- 官方提供
private void parseJSONObject(String jsonData) {
try {
JSONArray jsonArray = new JSONArray(jsonData);
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.d("MainActivity", "id is " + id);
Log.d("MainActivity", "name is " + name);
Log.d("MainActivity", "version is " + version);
}
} catch (Exception e) {
e.printStackTrace();
}
}
GSON
- 添加依赖
'com.google.code.gson:gson:2.7'
- 解析一个到类
Gson gson = new Gson(); Person person = gson.fromJson(jsonData, Person.class);
- 解析一段
List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>(){}.getType());
private void parseJSONWithGSON(String jsonData) {
Gson gson = new Gson();
List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>(){}.getType());
for (App app : appList) {
Log.d("MainActivity", "id is " + id);
Log.d("MainActivity", "name is " + name);
Log.d("MainActivity", "version is " + version);
}
}