Android 中的 SAXParser 并将输出存储到数组中

发布于 2024-11-29 02:42:16 字数 137 浏览 5 评论 0原文

我是新的 Android 开发人员,我想在 php 中创建一个 Web 服务,我想调用该 Web 服务和该响应以获取数组并填充到列表中。

提供最好的用户交互请帮助解决这个问题

提前感谢

@androidTechs

I am new android developer and i want create a webservice in php and i want call that webservice and that response in to get in array and that fill into List.

provideing the best user interaction pls help to solve this problems

Thanx in advance

@androidTechs

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

别忘他 2024-12-06 02:42:16

这是一个可用于调用名为 WebService.java 的 Web 服务的类

package com.blessan;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

public class WebService {

    private ArrayList <NameValuePair> params;
    private ArrayList <NameValuePair> headers;

    private String url;

    private int responseCode;
    private String message;

    private String response;

    public enum RequestMethod
    {
        GET,POST
    }

    public String getResponse() {
        return response;
    }

    public String getErrorMessage() {
        return message;
    }

    public int getResponseCode() {
        return responseCode;
    }

    public WebService(String url)
    {
        this.url = url;
        params = new ArrayList<NameValuePair>();
        headers = new ArrayList<NameValuePair>();
    }

    public void AddParam(String name, String value)
    {
        params.add(new BasicNameValuePair(name, value));
    }

    public void AddHeader(String name, String value)
    {
        headers.add(new BasicNameValuePair(name, value));
    }

    public void Execute(RequestMethod method) throws Exception
    {
        switch(method) {
            case GET:
            {
                //add parameters
                String combinedParams = "";
                if(!params.isEmpty()){
                    combinedParams += "?";
                    for(NameValuePair p : params)
                    {
                        String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
                        if(combinedParams.length() > 1)
                        {
                            combinedParams  +=  "&" + paramString;
                        }
                        else
                        {
                            combinedParams += paramString;
                        }
                    }
                }

                HttpGet request = new HttpGet(url + combinedParams);

                //add headers
                for(NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }

                executeRequest(request, url);
                break;
            }
            case POST:
            {
                HttpPost request = new HttpPost(url);

                //add headers
                for(NameValuePair h : headers)
                {   
                    request.addHeader(h.getName(), h.getValue());
                }

                if(!params.isEmpty()){
                    request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                }

                executeRequest(request, url);
                break;
            }
        }
    }

    private void executeRequest(HttpUriRequest request, String url) throws SocketTimeoutException, ConnectTimeoutException
    {
        HttpClient client = new DefaultHttpClient();
        HttpParams params = client.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);
        HttpResponse httpResponse;

        try {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();

            HttpEntity entity = httpResponse.getEntity();

            if (entity != null) {

                InputStream instream = entity.getContent();
                response = convertStreamToString(instream);

                // Closing the input stream will trigger connection release
                instream.close();
            }

        } catch (ClientProtocolException e)  {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        } catch(SocketTimeoutException e){
            client.getConnectionManager().shutdown();
            e.printStackTrace();
            throw new SocketTimeoutException();
        } catch(ConnectTimeoutException e){
            client.getConnectionManager().shutdown();
            e.printStackTrace();
            throw new ConnectTimeoutException();
        } catch (IOException e) {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        } catch (Exception e){
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        }
    }

    private static 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();
    }
}

这是您在活动中使用它的方法

WebService webClient = new WebService(Constants.REQUEST_URL);
        webClient.AddParam("method", "getUserLogin");
        webClient.AddParam("key", Constants.REQUEST_KEY);
        webClient.AddParam("xml_content","<Request>"+
                                             "<Authentication>"+
                                                 "<Username>"+StringEscapeUtils.escapeXml(userName.getText().toString().trim())+"</Username>"+
                                                 "<Password>"+StringEscapeUtils.escapeXml(passWord.getText().toString().trim())+"</Password>"+
                                                 "<AccountID>"+appContext.getCurrentAccount().accId+"</AccountID>"+
                                             "</Authentication>"+
                                             appContext.getDeviceInfo()+
                                         "</Request>");

        try {           
            webClient.Execute(WebService.RequestMethod.POST);
            String response = webClient.getResponse();
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            GetUserLoginHandler getUserLoginHandler = new GetUserLoginHandler();
            xr.setContentHandler(getUserLoginHandler);            
            InputSource input = new InputSource(new StringReader(response));
            xr.parse(input);           

            serverResponse = getUserLoginHandler.getResults();
            handler.sendEmptyMessage(0);
        } catch(SocketTimeoutException e){
            errorHandler.sendEmptyMessage(0);
        } catch(ConnectTimeoutException e){
            errorHandler.sendEmptyMessage(0);
        } catch (Exception e) {
            if(e.toString().indexOf("ExpatParser$ParseException") != -1){
                errorHandler.sendEmptyMessage(1);   
            } else {    
                errorHandler.sendEmptyMessage(0);
            }
        }

GetUserLoginHandler 是一个处理程序,用于解析此请求的响应。

package com.blessan;

import java.util.HashMap;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class GetUserLoginHandler extends DefaultHandler {
    private boolean in_statuscode    = false;
    private boolean in_statusmessage = false;
    private boolean in_userid        = false;
    private boolean in_username      = false;
    private boolean in_accountaccess = false;
    private boolean in_clockstatus   = false;
    private boolean in_timestamp     = false;
    private boolean in_depttransfer  = false;
    private boolean in_currdeptid    = false;
    private boolean in_currdeptname  = false;
    private Map<String, String> results         =   new HashMap<String, String>();

    @Override
    public void endDocument() throws SAXException {
    }

    @Override
    public void startElement(String namespaceURI, String localName,String qName, Attributes atts) throws SAXException {
        if (localName.equals("StatusCode")) {
            this.in_statuscode    = true;
        } else if (localName.equals("StatusMessage")) {
            this.in_statusmessage = true;
        } else if (localName.equals("UserId")) {
            this.in_userid        = true;
        } else if (localName.equals("UserName")) {
            this.in_username      = true;
        } else if (localName.equals("AccountAccess")) {
            this.in_accountaccess = true;
        } else if (localName.equals("ClockStatus")) {
            this.in_clockstatus   = true;
        } else if (localName.equals("Timestamp")) {
            this.in_timestamp     = true;
        } else if (localName.equals("DepartmentTransfer")) {
            this.in_depttransfer  = true;
        } else if (localName.equals("CurrentDepartmentID")) {
            this.in_currdeptid    = true;
        } else if (localName.equals("CurrentDepartmentName")) {
            this.in_currdeptname  = true;
        }
    }

    @Override
    public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
        if (localName.equals("StatusCode")) {
            this.in_statuscode    = false;
        } else if (localName.equals("StatusMessage")) {
            this.in_statusmessage = false;
        } else if (localName.equals("UserId")) {
            this.in_userid        = false;
        } else if (localName.equals("UserName")) {
            this.in_username      = false;
        } else if (localName.equals("AccountAccess")) {
            this.in_accountaccess = false;
        } else if (localName.equals("ClockStatus")) {
            this.in_clockstatus   = false;
        } else if (localName.equals("Timestamp")) {
            this.in_timestamp     = false;
        } else if (localName.equals("DepartmentTransfer")) {
            this.in_depttransfer  = false;
        } else if (localName.equals("CurrentDepartmentID")) {
            this.in_currdeptid    = false;
        } else if (localName.equals("CurrentDepartmentName")) {
            this.in_currdeptname  = false;
        }
    }

    @Override
    public void characters(char ch[], int start, int length) {
        if (this.in_statuscode) {
            results.put("StatusCode", new String(ch, start, length));
        } if (this.in_statusmessage) {
            results.put("StatusMessage", new String(ch, start, length));
        } if (this.in_userid) {
            results.put("UserId", new String(ch, start, length));
        } if (this.in_username) {
            results.put("UserName", new String(ch, start, length));
        } if (this.in_accountaccess) {
            results.put("AccountAccess", new String(ch, start, length));
        } if (this.in_clockstatus) {
            results.put("ClockStatus", new String(ch, start, length));
        } if (this.in_timestamp) {
            results.put("Timestamp", new String(ch, start, length));
        } if (this.in_depttransfer) {
            results.put("DepartmentTransfer", new String(ch, start, length));
        } if (this.in_currdeptid) {
            results.put("CurrentDepartmentID", new String(ch, start, length));
        } if (this.in_currdeptname) {
            results.put("CurrentDepartmentName", new String(ch, start, length));
        }
    }

    public Map<String, String> getResults(){
        return results;
    }
}

这只是一个例子。有很多教程详细解释了 SAX 解析。

This is a class that can be use to make call to webservice called WebService.java

package com.blessan;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

public class WebService {

    private ArrayList <NameValuePair> params;
    private ArrayList <NameValuePair> headers;

    private String url;

    private int responseCode;
    private String message;

    private String response;

    public enum RequestMethod
    {
        GET,POST
    }

    public String getResponse() {
        return response;
    }

    public String getErrorMessage() {
        return message;
    }

    public int getResponseCode() {
        return responseCode;
    }

    public WebService(String url)
    {
        this.url = url;
        params = new ArrayList<NameValuePair>();
        headers = new ArrayList<NameValuePair>();
    }

    public void AddParam(String name, String value)
    {
        params.add(new BasicNameValuePair(name, value));
    }

    public void AddHeader(String name, String value)
    {
        headers.add(new BasicNameValuePair(name, value));
    }

    public void Execute(RequestMethod method) throws Exception
    {
        switch(method) {
            case GET:
            {
                //add parameters
                String combinedParams = "";
                if(!params.isEmpty()){
                    combinedParams += "?";
                    for(NameValuePair p : params)
                    {
                        String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
                        if(combinedParams.length() > 1)
                        {
                            combinedParams  +=  "&" + paramString;
                        }
                        else
                        {
                            combinedParams += paramString;
                        }
                    }
                }

                HttpGet request = new HttpGet(url + combinedParams);

                //add headers
                for(NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }

                executeRequest(request, url);
                break;
            }
            case POST:
            {
                HttpPost request = new HttpPost(url);

                //add headers
                for(NameValuePair h : headers)
                {   
                    request.addHeader(h.getName(), h.getValue());
                }

                if(!params.isEmpty()){
                    request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                }

                executeRequest(request, url);
                break;
            }
        }
    }

    private void executeRequest(HttpUriRequest request, String url) throws SocketTimeoutException, ConnectTimeoutException
    {
        HttpClient client = new DefaultHttpClient();
        HttpParams params = client.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);
        HttpResponse httpResponse;

        try {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();

            HttpEntity entity = httpResponse.getEntity();

            if (entity != null) {

                InputStream instream = entity.getContent();
                response = convertStreamToString(instream);

                // Closing the input stream will trigger connection release
                instream.close();
            }

        } catch (ClientProtocolException e)  {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        } catch(SocketTimeoutException e){
            client.getConnectionManager().shutdown();
            e.printStackTrace();
            throw new SocketTimeoutException();
        } catch(ConnectTimeoutException e){
            client.getConnectionManager().shutdown();
            e.printStackTrace();
            throw new ConnectTimeoutException();
        } catch (IOException e) {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        } catch (Exception e){
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        }
    }

    private static 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();
    }
}

This is how you use it from your activity

WebService webClient = new WebService(Constants.REQUEST_URL);
        webClient.AddParam("method", "getUserLogin");
        webClient.AddParam("key", Constants.REQUEST_KEY);
        webClient.AddParam("xml_content","<Request>"+
                                             "<Authentication>"+
                                                 "<Username>"+StringEscapeUtils.escapeXml(userName.getText().toString().trim())+"</Username>"+
                                                 "<Password>"+StringEscapeUtils.escapeXml(passWord.getText().toString().trim())+"</Password>"+
                                                 "<AccountID>"+appContext.getCurrentAccount().accId+"</AccountID>"+
                                             "</Authentication>"+
                                             appContext.getDeviceInfo()+
                                         "</Request>");

        try {           
            webClient.Execute(WebService.RequestMethod.POST);
            String response = webClient.getResponse();
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            GetUserLoginHandler getUserLoginHandler = new GetUserLoginHandler();
            xr.setContentHandler(getUserLoginHandler);            
            InputSource input = new InputSource(new StringReader(response));
            xr.parse(input);           

            serverResponse = getUserLoginHandler.getResults();
            handler.sendEmptyMessage(0);
        } catch(SocketTimeoutException e){
            errorHandler.sendEmptyMessage(0);
        } catch(ConnectTimeoutException e){
            errorHandler.sendEmptyMessage(0);
        } catch (Exception e) {
            if(e.toString().indexOf("ExpatParser$ParseException") != -1){
                errorHandler.sendEmptyMessage(1);   
            } else {    
                errorHandler.sendEmptyMessage(0);
            }
        }

The GetUserLoginHandler is a handler used to parse the response for this request.

package com.blessan;

import java.util.HashMap;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class GetUserLoginHandler extends DefaultHandler {
    private boolean in_statuscode    = false;
    private boolean in_statusmessage = false;
    private boolean in_userid        = false;
    private boolean in_username      = false;
    private boolean in_accountaccess = false;
    private boolean in_clockstatus   = false;
    private boolean in_timestamp     = false;
    private boolean in_depttransfer  = false;
    private boolean in_currdeptid    = false;
    private boolean in_currdeptname  = false;
    private Map<String, String> results         =   new HashMap<String, String>();

    @Override
    public void endDocument() throws SAXException {
    }

    @Override
    public void startElement(String namespaceURI, String localName,String qName, Attributes atts) throws SAXException {
        if (localName.equals("StatusCode")) {
            this.in_statuscode    = true;
        } else if (localName.equals("StatusMessage")) {
            this.in_statusmessage = true;
        } else if (localName.equals("UserId")) {
            this.in_userid        = true;
        } else if (localName.equals("UserName")) {
            this.in_username      = true;
        } else if (localName.equals("AccountAccess")) {
            this.in_accountaccess = true;
        } else if (localName.equals("ClockStatus")) {
            this.in_clockstatus   = true;
        } else if (localName.equals("Timestamp")) {
            this.in_timestamp     = true;
        } else if (localName.equals("DepartmentTransfer")) {
            this.in_depttransfer  = true;
        } else if (localName.equals("CurrentDepartmentID")) {
            this.in_currdeptid    = true;
        } else if (localName.equals("CurrentDepartmentName")) {
            this.in_currdeptname  = true;
        }
    }

    @Override
    public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
        if (localName.equals("StatusCode")) {
            this.in_statuscode    = false;
        } else if (localName.equals("StatusMessage")) {
            this.in_statusmessage = false;
        } else if (localName.equals("UserId")) {
            this.in_userid        = false;
        } else if (localName.equals("UserName")) {
            this.in_username      = false;
        } else if (localName.equals("AccountAccess")) {
            this.in_accountaccess = false;
        } else if (localName.equals("ClockStatus")) {
            this.in_clockstatus   = false;
        } else if (localName.equals("Timestamp")) {
            this.in_timestamp     = false;
        } else if (localName.equals("DepartmentTransfer")) {
            this.in_depttransfer  = false;
        } else if (localName.equals("CurrentDepartmentID")) {
            this.in_currdeptid    = false;
        } else if (localName.equals("CurrentDepartmentName")) {
            this.in_currdeptname  = false;
        }
    }

    @Override
    public void characters(char ch[], int start, int length) {
        if (this.in_statuscode) {
            results.put("StatusCode", new String(ch, start, length));
        } if (this.in_statusmessage) {
            results.put("StatusMessage", new String(ch, start, length));
        } if (this.in_userid) {
            results.put("UserId", new String(ch, start, length));
        } if (this.in_username) {
            results.put("UserName", new String(ch, start, length));
        } if (this.in_accountaccess) {
            results.put("AccountAccess", new String(ch, start, length));
        } if (this.in_clockstatus) {
            results.put("ClockStatus", new String(ch, start, length));
        } if (this.in_timestamp) {
            results.put("Timestamp", new String(ch, start, length));
        } if (this.in_depttransfer) {
            results.put("DepartmentTransfer", new String(ch, start, length));
        } if (this.in_currdeptid) {
            results.put("CurrentDepartmentID", new String(ch, start, length));
        } if (this.in_currdeptname) {
            results.put("CurrentDepartmentName", new String(ch, start, length));
        }
    }

    public Map<String, String> getResults(){
        return results;
    }
}

This is just an example. There are many tutorials explaining SAX parsing in detail.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文