本Demo的简单截图
有关android调用WebService的流程
//实现该Demo需要用到
http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getMobileCodeInfo
//下面就是我贴的代码啦,很简单:
<!-- soap12.xml -->
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<getMobileCodeInfo xmlns="http://WebXml.com.cn/">
<mobileCode>$mobile</mobileCode>
<userID></userID>
</getMobileCodeInfo>
</soap12:Body>
</soap12:Envelope>
/*
* 将输入流转化为字节数组的工具*/
public class ReadPostSoap {
public static byte[] readsoap(InputStream inputStream){
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
byte[] b=new byte[1024];
int len=0;
try {
while ((len=inputStream.read(b))!=-1) {
outputStream.write(b, 0, len);
outputStream.flush();//涮新
}
return outputStream.toByteArray();
}
catch (Exception e) {
e.printStackTrace();
}finally{
if (inputStream!=null) {
try {
inputStream.close();//关闭
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream!=null) {
try {
outputStream.close();//关闭
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
/*
* 读取xml文件并调用webservice*/
public class SendDataToWebServiceThread extends Thread {
private String mobile;
private InputStream inputStream;
public SendDataToWebServiceThread(String mobile){
this.mobile=mobile;
inputStream=WebServiceDemo.class.getResourceAsStream("soap12.xml");
}
@Override
public void run() {
try {
byte[] b=ReadPostSoap.readsoap(inputStream);
String str=new String(b);
// str.replace(oldChar, newChar);//出错了,是字符与字符间的替换
str=str.replaceAll("\\$mobile", mobile);//‘\‘和‘$’都是特殊字符,需要转义
byte[] entity=str.getBytes();//转换后的字节数组
String path = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
conn.getOutputStream().write(entity);
if (conn.getResponseCode()==200) {
String pareString=Parsexml.parseSOAP(conn.getInputStream());
Log.e("-------------归属地查询-----------", pareString);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}