1.
| 代碼如下 |
複製代碼 |
| Webservice.GetVcardByUserNo(String userId,String userNo); |
這個是封裝了的webservice介面。
2.在程式中連續兩次調用該介面時,ksoap2在解析第二次調用返回的結果時拋異常。
異常資訊如下:
| 代碼如下 |
複製代碼 |
org.xmlpull.v1.XmlPullParserException: unexpected type (position:END_DOCUMENT null@1:0 in java.io.InputStreamReader@4383bf38)
|
3.打斷點調試時,不會出現該異常。
4.無奈之下使用android 的HttpURLConnection 直接調用webservice介面,直接使用時不會發生以上異常,所以使用ksoap2 訪問webservice需要設定什麼呢?
5.使用HttpUrlConnection訪問webserivice代碼如下:
(一)串連webservice
| 代碼如下 |
複製代碼 |
String ServerUrl="webservice地址"; String soapAction="http://www.111cn.net/PhoneClient/GetVcardJson"; String data=""; String requestData="<?xml version="1.0" encoding="utf-8"?>rn"+ "<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">rn" +"<soap:Header>rn"+ "<AuthHeader xmlns="http://www.111cn.net/PhoneClient/">rn"+ "<UserId>"+userID+"</UserId>rn"+ "</AuthHeader>rn"+ "</soap:Header>rn"+ "<soap:Body>rn"+ "<GetVcardJson xmlns="http://www.111cn.net/PhoneClient/">rn"+ "<vcardUserNo>"+userNo+"</vcardUserNo>rn"+ "</GetVcardJson>rn"+ "</soap:Body>rn"+ "</soap:Envelope>"; try{ URL url =new URL(ServerUrl); HttpURLConnection con=(HttpURLConnection)url.openConnection(); byte[] bytes=requestData.getBytes("utf-8"); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "text/xml;charset=utf-8"); con.setRequestProperty("SOAPAction",soapAction); con.setRequestProperty("Content-Length",""+bytes.length); OutputStream outStream=con.getOutputStream(); outStream.write(bytes); outStream.flush(); outStream.close(); InputStream inStream=con.getInputStream(); data=parser(inStream); |
(二)解析返回的資料
| 代碼如下 |
複製代碼 |
private static String parser(InputStream in){ XmlPullParser parser=Xml.newPullParser(); String data=""; try{ int flag=0; parser.setInput(in, "utf-8"); int evenType=parser.getEventType(); while(evenType!=XmlPullParser.END_DOCUMENT){ switch(evenType){ case XmlPullParser.START_DOCUMENT:break; case XmlPullParser.START_TAG: break; case XmlPullParser.TEXT: data=parser.getText(); break; case XmlPullParser.END_TAG:break; } parser.next(); evenType=parser.getEventType(); } }catch(XmlPullParserException e){ e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); } return data; } |