Android网络请求,数据解析及回调
单独依靠内置资源实现的App,在市场上不存在.通过用户的操作,向服务器发送请求,并将服务器返回的数据在App页面展现出来,是App运行的一般形式.App的正常运行就包括网络请求,数据解析,以及在同一线程执行任务时的回调.
两种网络请求:HttpURLConnection
和OkHttp
Android向服务器发送请求的方式很多,总体分为两类,一个是内置的HttpURLConnection,另外是基于HttpURLConnection的开源框架.开源框架中又属Square公司开源的OkHttp应用范围最广.
连接网络首先需要申请权限,在AndroidManifest.xml中添加:
<uses-permission android:name="android.permission.INTERNET"/>
获取HttpUrlConnection,比较简单,通过URL的openConnection方法可以创建.
private void getByUrlConnection(){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader = null;
try{
URL url = new URL("https://www.baidu.com");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setConnectTimeout(8000);
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(8000);
InputStream inputStream = urlConnection.getInputStream();
reader = new BufferedReader((new InputStreamReader(inputStream)));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null){
builder.append(line);
}
showResponse(builder.toString());
}catch (Exception e){
e.printStackTrace();
}finally {
if (reader != null){
try{
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (connection != null){
connection.disconnect();
}
}
}
}).start();
}
private void showResponse(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(response);
}
});
}
用户使用App期间,出现卡顿会严重影响用户体验,消耗时间的网络请求需要放在子线程执行.
也可以使用OkHttp发送请求:
private void getByOkHttp(){
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.baidu.com")
.get()
.build();
try{
Response response = client.newCall(request).execute();
String responseData = response.body().string();
showResponse(responseData);
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
数据请求中的两种形式:XML和Json
网络请求的数据需要按照一定的规则和协议,其中XML和Json两种数据形式,因为体积小,规则简单和实现方便得到了广泛的使用.
XML是Extensible Markup Language的简称,几乎可以在任何程序中进行数据交换.下面是一种简单的形式:
<apps>
<app>
<id>1</id>
<name>Chrome</name>
<version>1.0</version>
</app>
<app>
<id>2</id>
<name>Safari</name>
<version>1.0</version>
</app>
<app>
<id>3</id>
<name>FireFox</name>
<version>1.0</version>
</app>
</apps>
Android对XML的解析方式有Pull和SAX两种.它们本质都是对文件按行读取,按照元素标记的开头和结尾来获取元素的内容.
Pull解析XML
private void pullXML(String data){
try{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser pullParser = factory.newPullParser();
pullParser.setInput(new StringReader(data));
int eventType = pullParser.getEventType();
String id = "";
String name = "";
String version = "";
while (eventType != XmlPullParser.END_DOCUMENT){
String nodeName = pullParser.getName();
switch (eventType){
case XmlPullParser.START_TAG:{
if ("id".equals(nodeName)){
id = pullParser.nextText();
}else if ("name".equals(nodeName)){
name = pullParser.nextText();
}else if ("version".equals(nodeName)){
version = pullParser.nextText();
}
break;
}
case XmlPullParser.END_TAG:{
if ("app".equals(nodeName)){
Log.e("END_TAG", "id = " + id);
Log.e("END_TAG", "name = " + name);
Log.e("END_TAG", "version = " + version);
}
}
}
eventType = pullParser.next();
}
}catch (Exception e){
e.printStackTrace();
}
}
SAX解析XML
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 {
Log.e("startElement", "startElement: " + uri + localName + qName + attributes.toString());
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(localName)){
Log.e("endElement", "id = " + id);
Log.e("endElement", "name = " + name);
Log.e("endElement", "version = " + version);
id.setLength(0);
name.setLength(0);
version.setLength(0);
}
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
}
private void parseXmlUseSAX(String data){
SAXParserFactory factory = SAXParserFactory.newInstance();
try{
XMLReader xmlReader = factory.newSAXParser().getXMLReader();
ContentHandler contentH = new ContentHandler();
xmlReader.setContentHandler(contentH);
xmlReader.parse(new InputSource(new StringReader(data)));
}catch (Exception e){
e.printStackTrace();
}
}
Json是JavaScript Object Notation的简称,具有体积小,消耗流量少的特点,诞生于重视流量的移动端时代,二者的结合,让移动端更显流畅.Android系统包中自带了Json的的解析方式-JsonObject.Google开源的GSON解析Json也很方便.
JsonObject解析Json
private void parseJsonUseJsonObject(String data){
try{
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsObj = jsonArray.getJSONObject(i);
String id = jsObj.getString("id");
String name = jsObj.getString("name");
String version = jsObj.getString("version");
Log.e("parseJsonUseJsonObject", "parseJsonUseJsonObject: " + id + name + version);
}
}catch (Exception e){
e.printStackTrace();
}
}
GSON可以很方便地将Json格式的数据映射成对象,也即时MVC编程思想中的Model.
GSON解析Json
public class App {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
private String id;
private String name;
private String version;
}
private void parseJsonUseGson(String jsonData){
Gson gson = new Gson();
List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>(){}.getType());
for (App app: appList){
Log.e("App", "id: " + app.getId());
Log.e("App", "name: " + app.getName());
Log.e("App", "version: " + app.getVersion());
}
}
数据回调
App为了提高运行效率和更好的用户体验,使用了多线程技术,可以同时处理多个任务.比如常常用到的网络请求,就是在子线程中执行.子线程中的执行结果,可以通过数据回调的方式顺利实现任务的按序执行.
实现数据回调,首先需要定义接口,然后在子线程中使用.
//定义接口
public interface HttpCallbackListener {
void onFinish(String response);
void onError(Exception e);
}
//使用
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){
listener.onFinish(response.toString());
}
}catch (Exception e){
if (listener != null){
listener.onError(e);
}
}finally {
if (connection != null){
connection.disconnect();
}
}
}
}).start();
}
//调用
HttpUtil.SendHttpRequest("http://10.0.2.2/get_data.json", new HttpCallbackListener() {
@Override
public void onFinish(String response) {
parseJson(response);
}
@Override
public void onError(Exception e) {
}
});
总结
网络相关的知识,可以用3个二和1个一来概括:
两种网络请求方式HttpURLConnection和OkHttp;
两种数据传递方式XML和Json,其中XML的解析用Pull和SAX,Json的解析用JsonObject和GSON;
一种数据回调,通过接口(Interface)来实现.
喜欢和关注都是对我的鼓励和支持~