首先,說一下適用范圍:
當使用java版的webservice的時候,可以直接使用KSOAP2這個類庫,直接調用其方法就可以了。具體方法可以自行Google。
當使用.NET版的webservice的時候,KSOAP2這個類庫不是很好用,我研究了一個下午沒研究明白(可能是方法問題吧,歡迎大家共同交流)。 目的是獲取並解析復雜類型的返回值。
1.HttpConnSoap
[java]
<span style="font-size:14px;">package com.bottle.stockmanage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
public class HttpConnSoap {
public ArrayList<String> GetWebServre(String methodName, ArrayList<String> Parameters, ArrayList<String> ParValues) {
ArrayList<String> Values = new ArrayList<String>();
//ServerUrl是指webservice的url
//10.0.2.2是讓android模擬器訪問本地(PC)服務器,不能寫成127.0.0.1
//11125是指端口號,即掛載到IIS上的時候開啟的端口
//Service1.asmx是指提供服務的頁面
String ServerUrl = "http://10.0.2.2:11125/Service1.asmx";
//String soapAction="http://tempuri.org/LongUserId1";
String soapAction = "http://tempuri.org/" + methodName;
//String data = "";
String soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<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/\">"
+ "<soap:Body />";
String tps, vps, ts;
String mreakString = "";
mreakString = "<" + methodName + " xmlns=\"http://tempuri.org/\">";
for (int i = 0; i < Parameters.size(); i++) {
tps = Parameters.get(i).toString();
//設置該方法的參數為.net webService中的參數名稱
vps = ParValues.get(i).toString();
ts = "<" + tps + ">" + vps + "</" + tps + ">";
mreakString = mreakString + ts;
}
mreakString = mreakString + "</" + methodName + ">";
/*
+"<HelloWorld xmlns=\"http://tempuri.org/\">"
+"<x>string11661</x>"
+"<SF1>string111</SF1>"
+ "</HelloWorld>"
*/
String soap2 = "</soap:Envelope>";
String requestData = soap + mreakString + soap2;
//System.out.println(requestData);
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.setConnectTimeout(6000);// 設置超時時間
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);
//System.out.print("11");
Values = inputStreamtovaluelist(inStream, methodName);
//System.out.println(Values.size());
return Values;
} catch (Exception e) {
System.out.print("2221");
return null;
}
}
public ArrayList<String> inputStreamtovaluelist(InputStream in, String MonthsName) throws IOException {
StringBuffer out = new StringBuffer();
String s1 = "";
byte[] b = new byte[4096];
ArrayList<String> Values = new ArrayList<String>();
Values.clear();
for (int n; (n = in.read(b)) != -1;) {
s1 = new String(b, 0, n);
out.append(s1);
}
System.out.println(out);
String[] s13 = s1.split("><");
String ifString = MonthsName + "Result";
String TS = "";
String vs = "";
Boolean getValueBoolean = false;
for (int i = 0; i < s13.length; i++) {
TS = s13[i];
System.out.println(TS);
int j, k, l;
j = TS.indexOf(ifString);
k = TS.lastIndexOf(ifString);
if (j >= 0) {
System.out.println(j);
if (getValueBoolean == false) {
getValueBoolean = true;
} else {
}
if ((j >= 0) && (k > j)) {
System.out.println("FFF" + TS.lastIndexOf("/" + ifString));
//System.out.println(TS);
l = ifString.length() + 1;
vs = TS.substring(j + l, k - 2);
//System.out.println("fff"+vs);
Values.add(vs);
System.out.println("退出" + vs);
getValueBoolean = false;
return Values;
}
}
if (TS.lastIndexOf("/" + ifString) >= 0) {
getValueBoolean = false;
return Values;
}
if ((getValueBoolean) && (TS.lastIndexOf("/" + ifString) < 0) && (j < 0)) {
k = TS.length();
//System.out.println(TS);
vs = TS.substring(7, k - 8);
//System.out.println("f"+vs);
Values.add(vs);
}
}
return Values;
}
}
</span>
2.webservice的返回值
[html]
<span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?>
<ArrayOfReview xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<Review>
<userID>201311521412</userID>
<userName>wangjindong</userName>
<reviewInfo>哇咔咔哇咔咔哇咔咔</reviewInfo>
<reviewDate>2013-3-4 19:33:23</reviewDate>
</Review>
<Review>
<userID>201311521412</userID>
<userName>wangjindong</userName>
<reviewInfo>abcdefghijklmn</reviewInfo>
<reviewDate>2013/2/5 17:07:52</reviewDate>
</Review>
</ArrayOfReview></span>
可以看到,上面的返回的是一個list<Review>。這樣的話,用上面的那個HttpConnSoap就解析不了了。如果只看上面Values的值的話就是空的。這裡我們就要對HttpConnSoap類進行一些修改,同時,對這個類進行一下講解。
3.HttpConnSoap2
[java]
<span style="font-size:14px;">package com.pivotstudio.china.util;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import com.pivotstudio.china.config.AppConfig;
/**
* 連接webservice的類
*
* @author Bottle
*
* @Date 2013-3-19 下午10:01:21
*/
public class HttpConnSoap2
{
/**
* 獲取返回的InputStream,為了增強通用性,在方法內不對其進行解析。
*
* @param methodName
* webservice方法名
* @param Parameters
* webservice方法對應的參數名
* @param ParValues
* webservice方法中參數對應的值
* @return 未解析的InputStream
*/
public InputStream GetWebServre (String methodName, ArrayList<String> Parameters, ArrayList<String> ParValues)
{
//指定URL地址,我這裡使用的是常量。
//如:String ServerUrl = "http://10.0.2.2:11125/Service1.asmx";
String ServerUrl = AppConfig.ServerURL;
//soapAction = 命名空間 + 方法名
String soapAction = "http://tempuri.org/" + methodName;
//拼湊requestData
String soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<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/\">"
+ "<soap:Body />";
String tps, vps, ts;
String mreakString = "";
mreakString = "<" + methodName + " xmlns=\"http://tempuri.org/\">";
for (int i = 0; i < Parameters.size(); i++)
{
tps = Parameters.get (i).toString();
//設置該方法的參數為.net webService中的參數名稱
vps = ParValues.get (i).toString();
ts = "<" + tps + ">" + vps + "</" + tps + ">";
mreakString = mreakString + ts;
}
mreakString = mreakString + "</" + methodName + ">";
String soap2 = "</soap:Envelope>";
String requestData = soap + mreakString + soap2;
//其上所有的數據都是在拼湊requestData,即向服務器發送的數據
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); //指定該鏈接是否只用caches
con.setConnectTimeout (6000); // 設置超時時間
con.setRequestMethod ("POST"); //指定發送方法名,包括Post和Get。
con.setRequestProperty ("Content-Type", "text/xml;charset=utf-8"); //設置(發送的)內容類型
con.setRequestProperty ("SOAPAction", soapAction); //指定soapAction
con.setRequestProperty ("Content-Length", "" + bytes.length); //指定內容長度
//發送數據
OutputStream outStream = con.getOutputStream();
outStream.write (bytes);
outStream.flush();
outStream.close();
//獲取數據
InputStream inputStream = con.getInputStream();
return inputStream;
/**
* 此類到此結束了,比原來的HttpConnSoap還短,因為這裡沒有對返回的數據做解析。數據完全都保存在了inputStream中。
* 而原來的類是將數據解析成了ArrayList
* <String>格式返回。顯然,這樣無法解決我們上面的需求(返回值是復雜類型的List)
*/
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
</span>
下面再簡單說一下如何解析上面返回的inputStream。
4.XMLParase
[java]
<span style="font-size:14px;">/**
* 利用xmlpull解析xml
*
* @author Bottle
*
* @Date 2013-3-22 下午4:53:35
*/
public class XMLParase
{
/**
* 解析評論xml信息
* @param inputStream
* @return
*/
public static ArrayList<CommentInfor> paraseCommentInfors (InputStream inputStream)
{
ArrayList<CommentInfor> list = new ArrayList<CommentInfor>();
XmlPullParser parser = Xml.newPullParser();
try
{
parser.setInput (inputStream, "UTF-8");
int eventType = parser.getEventType();
CommentInfor info = new CommentInfor();
while (eventType != XmlPullParser.END_DOCUMENT)
{
switch (eventType)
{
case XmlPullParser.START_DOCUMENT:// 文檔開始事件,可以進行數據初始化處理
break;
case XmlPullParser.START_TAG:// 開始元素事件
String name = parser.getName();
if (name.equalsIgnoreCase ("Review") )
{
info = new CommentInfor();
}
else if (name.equalsIgnoreCase ("userID") )
{
eventType = parser.next();
info.setUserID (parser.getText() );
}
else if (name.equalsIgnoreCase ("userName") )
{
eventType = parser.next();
info.setUserName (parser.getText() );
}
else if (name.equalsIgnoreCase ("reviewInfo") )
{
eventType = parser.next();
info.setReviewInfo (parser.getText() );
}
else if (name.equalsIgnoreCase ("reviewDate") )
{
eventType = parser.next();
info.setReviewDate (parser.getText() );
}
break;
case XmlPullParser.END_TAG:// 結束元素事件
if (parser.getName().equalsIgnoreCase ("Review") )
{
list.add (info);
info = null;
}
break;
}
eventType = parser.next();
}
inputStream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return list;
}
}
</span>
其實就是利用xmlpull解析xml,具體可以視需求而定。
調用的時候只需如下。
[java]
<span style="font-size:14px;">HttpConnSoap2 webservice = new HttpConnSoap2();
String methodName = "showReview";//方法名
ArrayList<String> paramList = new ArrayList<String>();
ArrayList<String> parValueList = new ArrayList<String>();
ArrayList<CommentInfor>() resultList = new ArrayList<CommentInfor>();
paramList.add ("ID");//指定參數名
parValueList.add ("001");//指定參數值
InputStream inputStream = webservice.GetWebServre (methodName, paramList, parValueList);
resultList = XMLParase.paraseCommentInfors (inputStream);</span>