android中的SAXParser,并将输出存储到数组中
我是新的android开发者,我想用php创建一个Web服务,我想调用该Web服务和响应以进入数组并填充到列表中 提供最佳的用户交互有助于解决此问题 先发制人android中的SAXParser,并将输出存储到数组中,android,saxparser,Android,Saxparser,我是新的android开发者,我想用php创建一个Web服务,我想调用该Web服务和响应以进入数组并填充到列表中 提供最佳的用户交互有助于解决此问题 先发制人 @androidTechs这是一个可以用来调用webservice的类,名为webservice.java package com.blessan; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import
@androidTechs这是一个可以用来调用webservice的类,名为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();
}
}
package com.blessan;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.net.SocketTimeoutException;
导入java.net.urlcoder;
导入java.util.ArrayList;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.client.methods.HttpUriRequest;
导入org.apache.http.conn.ConnectTimeoutException;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.message.BasicNameValuePair;
导入org.apache.http.params.HttpConnectionParams;
导入org.apache.http.params.HttpParams;
导入org.apache.http.protocol.http;
公共类Web服务{
私有数组列表参数;
私有数组列表头;
私有字符串url;
私人内部响应代码;
私有字符串消息;
私有字符串响应;
公共枚举请求方法
{
得到,邮寄
}
公共字符串getResponse(){
返回响应;
}
公共字符串getErrorMessage(){
返回消息;
}
public int getResponseCode(){
返回响应代码;
}
公共Web服务(字符串url)
{
this.url=url;
params=新的ArrayList();
headers=newarraylist();
}
public void AddParam(字符串名称、字符串值)
{
添加(新的BasicNameValuePair(名称、值));
}
public void AddHeader(字符串名称、字符串值)
{
添加(新的BasicNameValuePair(名称、值));
}
public void Execute(RequestMethod)引发异常
{
开关(方法){
案例获取:
{
//添加参数
字符串组合参数=”;
如果(!params.isEmpty()){
组合参数+=“?”;
用于(名称值对p:params)
{
字符串paramString=p.getName()+“=”+urlcoder.encode(p.getValue(),“UTF-8”);
如果(combinedParams.length()>1)
{
组合参数+=“&”+参数字符串;
}
其他的
{
combinedParams+=paramString;
}
}
}
HttpGet请求=新的HttpGet(url+组合参数);
//添加标题
对于(NameValuePair h:Header)
{
addHeader(h.getName(),h.getValue());
}
executeRequest(请求、url);
打破
}
个案职位:
{
HttpPost请求=新的HttpPost(url);
//添加标题
对于(NameValuePair h:Header)
{
addHeader(h.getName(),h.getValue());
}
如果(!params.isEmpty()){
setEntity(新的UrlEncodedFormEntity(params,HTTP.UTF_8));
}
executeRequest(请求、url);
打破
}
}
}
私有void executeRequest(HttpUriRequest请求,字符串url)抛出SocketTimeoutException、ConnectTimeoutException
{
HttpClient=new DefaultHttpClient();
HttpParams params=client.getParams();
HttpConnectionParams.setConnectionTimeout(参数,10000);
HttpConnectionParams.setSoTimeout(参数,10000);
HttpResponse HttpResponse;
试一试{
httpResponse=client.execute(请求);
responseCode=httpResponse.getStatusLine().getStatusCode();
message=httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity=httpResponse.getEntity();
如果(实体!=null){
InputStream instream=entity.getContent();
响应=转换流至管柱(流内);
//关闭输入流将触发连接释放
流内关闭();
}
}捕获(客户端协议例外e){
client.getConnectionManager().shutdown();
e、 printStackTrace();
}捕获(SocketTimeoutException e){
client.getConnectionManager().shutdown();
e、 printStackTrace();
抛出新的SocketTimeoutException();
}捕获(ConnectTimeoutException e){
client.getConnectionManager().shutdown();
e、 printStackTrace();
抛出新的ConnectTimeoutException();
}捕获(IOE异常){
client.getConnectionManager().shutdown();
e、 printStackTrace();
}捕获(例外e){
client.getConnectionManager().shutdown();
e、 printStackTrace();
}
}
私有静态字符串convertStreamToString(InputStream为){
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is));
StringBuilder sb=新的StringBuilder();
字符串行=null;
试一试{
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
}捕获(IOE异常){
e、 printStackTrace();
}最后
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);
}
}
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;
}
}