Department of famous Gate Android (10) - HTTP communication, XML parsing, through asynchronous message processing Hander
Advertisements
Author: webabcd
Describes the Android do with the server-side HTTP communication, parsing XML, asynchronous message processing through the Handler
HTTP traffic - to do with the server-side HTTP communication, respectively GET method and POST method for demonstration
XML parsing - can be two ways to parse XML, namely the DOM and SAX mode means asynchronous message processing - by Handler asynchronous message processing, to a custom asynchronous download class to illustrate the usage of Handler
1, HTTP communication and XML parsing Demo
MySAXHandler.java
Code
package com.webabcd.communication;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
// Inheritance DefaultHandler for specifying the XML SAX parser
// DOM - W3C Standard, it is required to load the xml data is fully completed before it can be resolved, you can make arbitrary traversal
// SAX - Streaming resolution, with the event model for parsing XML, you can only order analysis
public class MySAXHandler extends DefaultHandler {
private boolean mIsTitleTag = false;
private boolean mIsSalaryTag = false;
private boolean mIsBirthTag = false;
private String mResult = "";
// Open XML document of a callback function
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
super.startDocument();
}
// Close the XML document of a callback function
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
super.endDocument();
}
// Finding an element start tag is callback this function
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (localName == "title")
mIsTitleTag = true;
else if (localName == "salary")
mIsSalaryTag = true;
else if (localName == "dateOfBirth")
mIsBirthTag = true;
else if (localName == "employee")
mResult += "\nname:" + attributes.getValue("name");
}
// A discovery element end tag is callback this function
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName == "title")
mIsTitleTag = false;
else if (localName == "salary")
mIsSalaryTag = false;
else if (localName == "dateOfBirth")
mIsBirthTag = false;
}
// A discovery of element value, or property value for this function is a callback
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (mIsTitleTag)
mResult += new String(ch, start, length);
else if (mIsSalaryTag)
mResult += " salary:" + new String(ch, start, length);
else if (mIsBirthTag)
mResult += " dateOfBirth:" + new String(ch, start, length);
}
public String getResult(){
return mResult;
}
}
Main.java
Code
package com.webabcd.communication;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EncodingUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity {
private TextView textView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) this.findViewById(R.id.textView);
Button btn1 = (Button) this.findViewById(R.id.btn1);
btn1.setText("http get demo");
btn1.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
httpGetDemo();
}
});
Button btn2 = (Button) this.findViewById(R.id.btn2);
btn2.setText("http post demo");
btn2.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
httpPostDemo();
}
});
Button btn3 = (Button) this.findViewById(R.id.btn3);
// DOM - Document Object Model
btn3.setText("DOM Parsing XML ");
btn3.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
DOMDemo();
}
});
Button btn4 = (Button) this.findViewById(R.id.btn4);
// SAX - Simple API for XML
btn4.setText("SAX Parsing XML ");
btn4.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
SAXDemo();
}
});
}
// Android Call the get method of the HTTP protocol
// Example: to the HTTP Protocol's get method gets the contents of the remote page response
private void httpGetDemo(){
try {
// Simulator tests, use the external network address
URL url = new URL("http://xxx.xxx.xxx");
URLConnection con = url.openConnection();
String result = "http status code: " + ((HttpURLConnection)con).getResponseCode() + "\n";
// HttpURLConnection.HTTP_OK
InputStream is = con.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer bab = new ByteArrayBuffer(32);
int current = 0;
while ( (current = bis.read()) != -1 ){
bab.append((byte)current);
}
result += EncodingUtils.getString(bab.toByteArray(), HTTP.UTF_8);
bis.close();
is.close();
textView.setText(result);
} catch (Exception e) {
textView.setText(e.toString());
}
}
// Android Call of the HTTP protocol that the post method
// Example: to the HTTP protocol of the post method to pass parameters to a remote page, and gets its response
private void httpPostDemo(){
try {
// Simulator tests, use the external network address
String url = "http://5billion.com.cn/post.php";
Map<String, String> data = new HashMap<String, String>();
data.put("name", "webabcd");
data.put("salary", "100");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
ArrayList<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
for (Map.Entry<String, String> m : data.entrySet()) {
postData.add(new BasicNameValuePair(m.getKey(), m.getValue()));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
String result = "http status code: " + response.getStatusLine().getStatusCode() + "\n";
// HttpURLConnection.HTTP_OK
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
result += convertStreamToString(is);
textView.setText(result);
} catch (Exception e) {
textView.setText(e.toString());
}
}
// To parse the XML DOM method (XML data as described in the res /raw/employee.xml )
private void DOMDemo(){
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(this.getResources().openRawResource(R.raw.employee));
Element rootElement = doc.getDocumentElement();
NodeList employeeNodeList = rootElement.getElementsByTagName("employee");
textView.setText("DOMDemo" + "\n");
String title = rootElement.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();
textView.append(title);
for (int i=0; i<employeeNodeList.getLength(); i++){
Element employeeElement = ((Element)employeeNodeList.item(i));
String name = employeeElement.getAttribute("name");
String salary = employeeElement.getElementsByTagName("salary").item(0).getFirstChild().getNodeValue();
String dateOfBirth = employeeElement.getElementsByTagName("dateOfBirth").item(0).getFirstChild().getNodeValue();
textView.append("\nname: "+name+" salary: "+salary+" dateOfBirth: " + dateOfBirth);
}
} catch (Exception e) {
textView.setText(e.toString());
}
}
// To parse the XML SAX method (XML data as described in the res /raw/employee.xml )
// SAX Parser implementation as described in MySAXHandler .java
private void SAXDemo(){
try {
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
SAXParser parser = saxFactory.newSAXParser();
XMLReader reader = parser.getXMLReader();
MySAXHandler handler = new MySAXHandler();
reader.setContentHandler(handler);
reader.parse(new InputSource(this.getResources().openRawResource(R.raw.employee)));
String result = handler.getResult();
textView.setText("SAXDemo" + "\n");
textView.append(result);
} catch (Exception e) {
textView.setText(e.toString());
}
}
// A secondary method used to convert a string to a stream
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
2 , Use Handler to implement asynchronous message processing to a real-time reporting to the download progress of an asynchronous download class as an example
To develop an Android class library, this case this class library named webabcd _util
New -> Java Project
Right-click on the project -> Build Path -> Add Libraries -> User Library -> User Libraries -> New -> A name for the class -> Select the class library -> Add JARs Import Android jar package
Right-click on the project -> Build Path -> Add Libraries -> User Library -> Select Android library
DownloadManagerAsync.java
Code
package webabcd.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.protocol.HTTP;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
// In one instance, the asynchronous download demonstrates an Android asynchronous message processing (Handler)
public class DownloadManagerAsync {
public DownloadManagerAsync() {
}
// Instantiate the custom Handler
EventHandler mHandler = new EventHandler(this);
// According to the specified URL address to download the file to the specified path
public void download(final String url, final String savePath) {
new Thread(new Runnable() {
public void run() {
try {
sendMessage(FILE_DOWNLOAD_CONNECT);
URL sourceUrl = new URL(url);
URLConnection conn = sourceUrl.openConnection();
InputStream inputStream = conn.getInputStream();
int fileSize = conn.getContentLength();
File savefile = new File(savePath);
if (savefile.exists()) {
savefile.delete();
}
savefile.createNewFile();
FileOutputStream outputStream = new FileOutputStream(
savePath, true);
byte[] buffer = new byte[1024];
int readCount = 0;
int readNum = 0;
int prevPercent = 0;
while (readCount < fileSize && readNum != -1) {
readNum = inputStream.read(buffer);
if (readNum > -1) {
outputStream.write(buffer);
readCount = readCount + readNum;
int percent = (int) (readCount * 100 / fileSize);
if (percent > prevPercent) {
// Send a download progress information
sendMessage(FILE_DOWNLOAD_UPDATE, percent,
readCount);
prevPercent = percent;
}
}
}
outputStream.close();
sendMessage(FILE_DOWNLOAD_COMPLETE, savePath);
} catch (Exception e) {
sendMessage(FILE_DOWNLOAD_ERROR, e);
Log.e("MyError", e.toString());
}
}
}).start();
}
// Reads the specified response content url address
public void download(final String url) {
new Thread(new Runnable() {
public void run() {
try {
sendMessage(FILE_DOWNLOAD_CONNECT);
URL sourceUrl = new URL(url);
URLConnection conn = sourceUrl.openConnection();
conn.setConnectTimeout(3000);
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(),
HTTP.UTF_8));
String line = null;
StringBuffer content = new StringBuffer();
while ((line = reader.readLine()) != null) {
content.append(line);
}
reader.close();
sendMessage(FILE_DOWNLOAD_COMPLETE, content.toString());
} catch (Exception e) {
sendMessage(FILE_DOWNLOAD_ERROR, e);
Log.e("MyError", e.toString());
}
}
}).start();
}
// Send a message to a Handler
private void sendMessage(int what, Object obj) {
// Needs a message sent to the Handler
Message msg = mHandler.obtainMessage(what, obj);
// Send message
mHandler.sendMessage(msg);
}
private void sendMessage(int what) {
Message msg = mHandler.obtainMessage(what);
mHandler.sendMessage(msg);
}
private void sendMessage(int what, int arg1, int arg2) {
Message msg = mHandler.obtainMessage(what, arg1, arg2);
mHandler.sendMessage(msg);
}
private static final int FILE_DOWNLOAD_CONNECT = 0;
private static final int FILE_DOWNLOAD_UPDATE = 1;
private static final int FILE_DOWNLOAD_COMPLETE = 2;
private static final int FILE_DOWNLOAD_ERROR = -1;
// A custom Handler
private class EventHandler extends Handler {
private DownloadManagerAsync mManager;
public EventHandler(DownloadManagerAsync manager) {
mManager = manager;
}
// Process the received messages
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case FILE_DOWNLOAD_CONNECT:
if (mOnDownloadConnectListener != null)
mOnDownloadConnectListener.onDownloadConnect(mManager);
break;
case FILE_DOWNLOAD_UPDATE:
if (mOnDownloadUpdateListener != null)
mOnDownloadUpdateListener.onDownloadUpdate(mManager,
msg.arg1);
break;
case FILE_DOWNLOAD_COMPLETE:
if (mOnDownloadCompleteListener != null)
mOnDownloadCompleteListener.onDownloadComplete(mManager,
msg.obj);
break;
case FILE_DOWNLOAD_ERROR:
if (mOnDownloadErrorListener != null)
mOnDownloadErrorListener.onDownloadError(mManager,
(Exception) msg.obj);
break;
default:
break;
}
}
}
// Define connection events
private OnDownloadConnectListener mOnDownloadConnectListener;
public interface OnDownloadConnectListener {
void onDownloadConnect(DownloadManagerAsync manager);
}
public void setOnDownloadConnectListener(OnDownloadConnectListener listener) {
mOnDownloadConnectListener = listener;
}
// Define the download progress update event
private OnDownloadUpdateListener mOnDownloadUpdateListener;
public interface OnDownloadUpdateListener {
void onDownloadUpdate(DownloadManagerAsync manager, int percent);
}
public void setOnDownloadUpdateListener(OnDownloadUpdateListener listener) {
mOnDownloadUpdateListener = listener;
}
// Download the complete event defined
private OnDownloadCompleteListener mOnDownloadCompleteListener;
public interface OnDownloadCompleteListener {
void onDownloadComplete(DownloadManagerAsync manager, Object result);
}
public void setOnDownloadCompleteListener(
OnDownloadCompleteListener listener) {
mOnDownloadCompleteListener = listener;
}
// Define download exception events
private OnDownloadErrorListener mOnDownloadErrorListener;
public interface OnDownloadErrorListener {
void onDownloadError(DownloadManagerAsync manager, Exception e);
}
public void setOnDownloadErrorListener(OnDownloadErrorListener listener) {
mOnDownloadErrorListener = listener;
}
}
Call the above custom Android class library
Right-click on the project -> Properties -> Java Build Path -> Projects -> Add The class library reference above
Main.java
Code
package com.webabcd.handler;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import webabcd.util.DownloadManagerAsync;
public class Main extends Activity implements
DownloadManagerAsync.OnDownloadCompleteListener,
DownloadManagerAsync.OnDownloadUpdateListener,
DownloadManagerAsync.OnDownloadErrorListener {
TextView txt;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DownloadManagerAsync manager = new DownloadManagerAsync();
manager.setOnDownloadCompleteListener(this);
manager.setOnDownloadUpdateListener(this);
manager.download("http://files.cnblogs.com/webabcd/Android.rar", "/sdcard/Android.rar");
txt = (TextView) this.findViewById(R.id.txt);
txt.setText(" To start the download. ");
}
public void onDownloadComplete(DownloadManagerAsync manager, Object result) {
txt.setText(" Download the complete ");
}
public void onDownloadUpdate(DownloadManagerAsync manager, int percent) {
txt.setText(" Download progress: " + String.valueOf(percent) + "%");
}
public void onDownloadError(DownloadManagerAsync manager, Exception e) {
txt.setText(" There was an error downloading ");
}
}
Related Posts of Department of famous Gate Android (10) - HTTP communication, XML parsing, through asynchronous message processing Hander
-
To a generic hibernate example DAO
Reprint: http://blog.csdn.net/dingx package sgf4web.dao; import java.io.Serializable; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.hibernate.*; import org.hibernate.criterion.*; import org.springframework.
-
hibernate (jpa) composite primary key annotation statement Ways
In the design of the database tables are designed with a composite primary key of the table, that table's record by more than one field joint identification, such as: Table CREATE TABLE TB_HOUR_DATA ( STAT_DATE DATE NOT NULL, PATH_ID NUMBER(20) NOT NULL,
-
log4j easy application in java
JAVA development, frequently used the log output, in a so-called most of the software company will have its own set of configuration style, re-read the configuration file to initialize property of the log, it will be good, but sometimes may not need to fu
-
jboss ejb3 Message Driven Bean
Super Medium ejb hate. . . . . . . . . . . . . . . . . . . ================================================ To configure a Message Driven Bean in a different application server parameters are not the same. Currently only passed the test jboss. Message Dri
-
java read file
java read documents in two ways: java.io and java.lang.ClassLoader When using the java.io, when java.lang.ClassLoader use it? (Note: If prior to read xml file java read file clearly aware of these two methods have been like! Can take much less to understa
-
hibernate generic generic DAO
package org.lzpeng.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *
-
First Hibernate Example
Curd a simple example. Source does not contain the dependent libraries, or playing too much of the package. PO object Note: One must have the default constructor 2 non-final modified. Otherwise useless lazy loading. UserDAOImpl category code, and other co
-
Spring2.0 + hibernate3.1 + log4j + mysql demo
applicationContext.xml Non-attachment jar package, necessary friends can send an email to todd.liangt @ gmail.com
-
Great collection of java interview topics
1, object-oriented features of what has 1. Abstract: Abstract is that it has overlooked a subject has nothing to do with the current goal of those aspects in order to more fully with the current objectives of the attention-related aspects. Abstract does n












