Department of famous Gate Android (10) - HTTP communication, XML parsing, through asynchronous message processing Hander

Department of famous Gate Android (10) - HTTP communication, XML parsing, through asynchronous message processing Hander

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  ");
    }
}
分类:Mobile 时间:2010-03-29 人气:558
分享到:
blog comments powered by Disqus

相关文章

  • public void testStatementAddBatch () public void testConnCommit () 2011-09-01

    public void testStatementAddBatch() { Connection conn = null; Statement stmt = null; try { conn = getDBConnectionMsSqlBySuperAdmin(); stmt = conn.createStatement(); for(int i = 0; i < 100; i++) { String sql = " sql " + i; stmt.addBatch(sql);

  • Import and export data in SQL Server, Comparison of three 2010-09-17

    When we create a database, and will be dispersed to different types of databases subtotals in the newly created database, especially when conducting data validation, purification and conversion, will face great challenges. Fortunately, SQL Server pro

  • Android uses [AIDL] call an external service 2010-10-19

    Android calls using an external service] [AIDL In Android, each application can have its own process. When writing a UI application, often use the Service. In a different process, how to pass objects? Clearly, Java is not allowed to share memory acro

  • AIDL --- Android's remote interface 2011-01-13

    In Android, each application can have its own process. When writing a UI application, often use the Service. In a different process, how to pass objects? Clearly, Java is not allowed to share memory across processes. So pass the object, the object ca

  • JavaMail Application 2010-03-29

    Transfer from: http://www.blogjava.net/BlueSUN/archive/2007/04/18/111750.html I do have a little software development for years, look back and think, has gone through a lot of ups and downs, in order to solve complex problems than pleasure. Also work

  • poj1915 2010-03-29

    Reiteration: Background fabulous chess player Somurolov President, he claimed that he could be a knight to move quickly from one location to another location, but others can not. Can you beat him? Problems in your job is to write a program to calcula

  • [How Tomcat Works] Chapter 2, a simple Servlet Container 2008-10-10

    Translator jarfield Blog http://jarfield.javaeye.com Overview javax.servlet.Servlet Interface First application HttpServer1 class Request Class Response Class StaticResourceProcessor class ServletProcessor1 class Running Applications The second appli

  • Secure multi-threaded - Multi-Threaded with BlockingQueue 2010-03-22

    Article by: Jeff Langr Writing well-behaved, multi-threaded applications is one of the more challenging aspects of Java coding.One of the best ways to write multi-threaded applications is to take advantage of known threading patterns.Queues are commo

  • Introduction to J2ME experience 2010-04-01

    Learning J2ME has been a few days, and today I a beginner's perspective on how to learn J2ME I remember the first time I read the book J2ME time I'm going to candidates in the company's J2ME developers xxx job the day before the interview day to day

  • Improvement on the IBatis page to ibatis hibernate type of physical support page - is reproduced 2010-04-01

    Keywords: ibatis spring physical paging paging Most of our projects have started using IBatis as O / R Mapping, but also in the process of discovery using a lot of inconvenience and controversial area, which is a convenient place to paging, the prese

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.201 (s). 15 q(s)