Android开发之如何调用WebService

以如何根据一个手机号码获取号码归属地为例,详细地讲解一下WebService的调用
这里使用的WebService提供站是
我们用的是soap1.2协议,根据以上网页中的soap1.2实例来编写代码

SOAP 1.2

以下是 SOAP 1.2 请求和响应示例。所显示的占位符需替换为实际值。

POST /WebServices/MobileCodeWS.asmx HTTP/1.1
Host: webservice.webxml.com.cn
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length

<?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>string</mobileCode>
      <userID>string</userID>
    </getMobileCodeInfo>
  </soap12:Body>
</soap12:Envelope>

HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length

<?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>
    <getMobileCodeInfoResponse xmlns="http://WebXml.com.cn/">
      <getMobileCodeInfoResult>string</getMobileCodeInfoResult>
    </getMobileCodeInfoResponse>
  </soap12:Body>
</soap12:Envelope>

我们要发送的是一个post请求,完整的路径为
http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx
发送的数据为
<?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>string</mobileCode>
      <userID>string</userID>
    </getMobileCodeInfo>
  </soap12:Body>
</soap12:Envelope>
为此我们要先写一个mobilesoap.xml文件,将第一个string改成手机号码(我们可以在xml文件中用占位符来表示),第二个string可以置空(表示免费用户)
将这些数据以http/post请求发送给服务器,服务器将返回一个响应,响应格式上面已经指出,通过解析响应的数据,就可以得到手机号码的归属地了
第一步,首先要读取我们自己定义的带有占位符的mobilesoap.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>
以上是mobilesoap.xml文件中的内容
private static String readSoapFile(InputStream inStream, String mobile) throws Exception{
byte[] data = StreamTool.readInputStream(inStream);
String soapxml = new String(data);
Map<String, String> params = new HashMap<String, String>();
params.put("mobile", mobile);
return replace(soapxml, params);
}
public static String replace(String xml, Map<String, String> params)throws Exception{
String result = xml;
if(params!=null && !params.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
String name = "\\$"+ entry.getKey();
Pattern pattern = Pattern.compile(name);
Matcher matcher = pattern.matcher(result);
if(matcher.find()){
result = matcher.replaceAll(entry.getValue());
}
}
}
return result;
}
以上代码就可以根据mobilesoap.xml输入流以及 mobile参数构造出完整的基于soap的http请求中的数据部分,将这些数据加上请求头发送给服务器,服务器就可以返回我们所需要的归属地数据了
public static String getMobileAddress(InputStream inStream, String mobile)throws Exception{
String soap = readSoapFile(inStream, mobile);
byte[] data = soap.getBytes();
URL url = new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5 * 1000);
conn.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据
conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
if(conn.getResponseCode()==200){
return parseResponseXML(conn.getInputStream());
}
return null;
}
       
private static String parseResponseXML(InputStream inStream) throws Exception{
XmlPullParser parser = Xml.newPullParser();
parser.setInput(inStream, "UTF-8");
int eventType = parser.getEventType();//产生第一个事件
while(eventType!=XmlPullParser.END_DOCUMENT){//只要不是文档结束事件
switch (eventType) {
case XmlPullParser.START_TAG:
String name = parser.getName();//获取解析器当前指向的元素的名称
if("getMobileCodeInfoResult".equals(name)){
return parser.nextText();
}
break;
}
eventType = parser.next();
}
return null;
}

最后在我们的Activity就可以调用这些方法了,Activity简单界面如下
Android开发之如何调用WebService
图 1
为此我们将这些方法定义在MobileAddressService类里面,然后就可以调用了
public class MainActivity extends Activity {
    public static final String TAG = "MainActivity";
    private EditText txt_mobile;
    private Button btn_search;
    private TextView lab_mobile;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        txt_mobile = (EditText) findViewById(R.id.txt_mobile);
        btn_search = (Button) findViewById(R.id.btn_search);
        lab_mobile = (TextView) findViewById(R.id.mobile_address);
        btn_search.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String mobileNum = txt_mobile.getText().toString();
InputStream inStream = getClass().getClassLoader().getResourceAsStream("mobilesoap.xml");
try {
String mobileAddress = MobileAddressService.getMobileAddress(inStream, mobileNum);
lab_mobile.setText(mobileAddress);
} catch (Exception e) {
Toast.makeText(MainActivity.this, "获取归属地失败!", 1);
Log.e(TAG,"获取归属地失败!");
}
}
});
        
    }
}
至此,有关webservice调用阐述完毕!








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值