Android手机端调用webservice来获得手机归属地号码

1:原理解析

   我们通过soap协议来调用http://www.webxml.com.cn/zh_cn/index.aspx 

 

android端需要发送的数据信息,也是协议信息

[html]  view plain copy
  1. POST /WebServices/MobileCodeWS.asmx HTTP/1.1  
  2. Host: webservice.webxml.com.cn  
  3. Content-Type: application/soap+xml; charset=utf-8  
  4. Content-Length: length  
  5.   
  6. <?xml version="1.0" encoding="utf-8"?>  
  7. <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">  
  8.   <soap12:Body>  
  9.     <getMobileCodeInfo xmlns="http://WebXml.com.cn/">  
  10.       <mobileCode><span style="color:#ff0000;">string</span></mobileCode>  
  11.       <userID><span style="color:#ff0000;">string</span></userID>  
  12.     </getMobileCodeInfo>  
  13.   </soap12:Body>  
  14. </soap12:Envelope>  


    以上是通过发送POST协议来调用webservice,通过下面定义的xml数据来调用服务器端的webservice,在下面的xml数据中,被红色标识的部分需要用户来填充,mobileCode是手机号码,userID为用户的id

 

服务器端返回的信息:

[html]  view plain copy
  1. HTTP/1.1 200 OK  
  2. Content-Type: application/soap+xml; charset=utf-8  
  3. Content-Length: length  
  4.   
  5. <?xml version="1.0" encoding="utf-8"?>  
  6. <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">  
  7.   <soap12:Body>  
  8.     <getMobileCodeInfoResponse xmlns="http://WebXml.com.cn/">  
  9.       <span style="color:#ff0000;"><getMobileCodeInfoResult>string</getMobileCodeInfoResult></span>  
  10.     </getMobileCodeInfoResponse>  
  11.   </soap12:Body>  
  12. </soap12:Envelope>  


   以上是服务器端返回的信息,标识部分代表返回的号码归属地的信息,可以通过解析xml数据来获得相关的信息

                                                                                                   android代码

2:用到的资源文件 strings.xml

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="hello">Hello World, MainActivity!</string>  
  4.     <string name="app_name">手机号归属地查询</string>  
  5.     <string name="mobile">手机号</string>  
  6.     <string name="button">查询</string>  
  7.     <string name="show">在此显示查询结果</string>  
  8. </resources>  

 

3:布局文件main.xml

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7.     <TextView    
  8.     android:layout_width="fill_parent"   
  9.     android:layout_height="wrap_content"   
  10.     android:text="@string/mobile"  
  11.     />  
  12.     <EditText   
  13.     android:layout_width="fill_parent"   
  14.     android:layout_height="wrap_content"   
  15.     android:id="@+id/mobile"  
  16.     />  
  17.     <Button   
  18.      android:layout_width="wrap_content"   
  19.      android:layout_height="wrap_content"   
  20.      android:id="@+id/button"  
  21.      android:text="@string/button"  
  22.     />  
  23.     <TextView  
  24.      android:layout_width="fill_parent"   
  25.      android:layout_height="wrap_content"   
  26.      android:id="@+id/address"  
  27.      android:text="@string/show"  
  28.     />  
  29. </LinearLayout>  

4:MainActivity的内容

[java]  view plain copy
  1. package com.capinfotech.mobileaddress;  
  2.   
  3. import java.io.InputStream;  
  4.   
  5. import com.capinfotech.mobile.service.MobileService;  
  6.   
  7. import android.app.Activity;  
  8. import android.os.Bundle;  
  9. import android.util.Log;  
  10. import android.view.View;  
  11. import android.widget.Button;  
  12. import android.widget.EditText;  
  13. import android.widget.TextView;  
  14. import android.widget.Toast;  
  15.   
  16. public class MainActivity extends Activity {  
  17.     private static final String TAG = "MainActivity";  
  18.     private EditText mobileEditText = null;  //输入的查询手机号  
  19.     private Button addressButton = null;     //查询按钮  
  20.     private TextView addressResult = null;   //显示查询的地址  
  21.     @Override  
  22.     public void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.main);  
  25.           
  26.         mobileEditText = (EditText)findViewById(R.id.mobile);  
  27.         addressButton = (Button)findViewById(R.id.button);  
  28.         addressResult = (TextView)findViewById(R.id.address);  
  29.           
  30.         addressButton.setOnClickListener(new View.OnClickListener() {  
  31.               
  32.             @Override  
  33.             public void onClick(View v) {  
  34.                 String mobile = mobileEditText.getText().toString();  
  35.                 InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("mobileaddress.xml");  
  36.                 Log.i(TAG, "inputStream: " + (inputStream == null));  
  37.                   
  38.                 try {  
  39.                     Log.i(TAG, "inputStream: " + inputStream.available());  
  40.                     String address = MobileService.getMobileAddress(inputStream, mobile);  
  41.                     Log.i(TAG, "address: " + address);  
  42.                     addressResult.setText(address);  
  43.                 } catch(Exception e) {  
  44.                     Log.e(TAG, e.toString());  
  45.                     Toast.makeText(MainActivity.this"网络异常", Toast.LENGTH_LONG).show();  
  46.                 }  
  47.             }  
  48.         });  
  49.     }  
  50. }  


5:MobileService类的内容

 

[java]  view plain copy
  1. package com.capinfotech.mobile.service;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.OutputStream;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.URL;  
  8. import java.util.HashMap;  
  9. import java.util.Map;  
  10. import java.util.regex.Matcher;  
  11. import java.util.regex.Pattern;  
  12.   
  13. import org.xmlpull.v1.XmlPullParser;  
  14. import org.xmlpull.v1.XmlPullParserException;  
  15.   
  16. import com.capinfotech.mobile.utils.StreamTool;  
  17.   
  18. import android.util.Log;  
  19. import android.util.Xml;  
  20.   
  21. public class MobileService {  
  22.     private static final String TAG = "MobileService";  
  23.     //根据inputStream和mobile(用户输入的手机号)来对文件mobileaddress.xml的mobile进行替换  
  24.     public static String readSoapFile(InputStream inputStream, String mobile) throws Exception {  
  25.         byte[] data = StreamTool.readInputStream(inputStream);  
  26.         Log.i(TAG, "datalength: " + data.length);  
  27.         String soapxml = new String(data);  
  28.         Log.i(TAG, "soapxml: " + soapxml);  
  29.         Map<String, String> params = new HashMap<String, String>();  
  30.         params.put("mobile", mobile);  
  31.         return replace(soapxml, params);  
  32.       
  33.     }  
  34.       
  35.     //完成替换的函数  
  36.     private static String replace(String xml, Map<String, String> params) throws Exception {  
  37.         String result = xml;  
  38.         if(params != null && !params.isEmpty()) {  
  39.             for(Map.Entry<String, String> entry: params.entrySet()) {  
  40.                 String name = "\\{1}quot; + entry.getKey();  
  41.                 Pattern pattern = Pattern.compile(name);  
  42.                 Matcher matcher = pattern.matcher(result);  
  43.                 if(matcher.find()) {  
  44.                     result = matcher.replaceAll(entry.getValue());  
  45.                 }  
  46.             }  
  47.         }  
  48.         return result;  
  49.     }  
  50.       
  51.     public static String getMobileAddress(InputStream inStream, String mobile) throws Exception {  
  52.         String soap = readSoapFile(inStream, mobile);  
  53.         byte[] data = soap.getBytes();  
  54.         URL url = new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");  
  55.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  56.         conn.setDoOutput(true);  //设置允许输出  
  57.         conn.setConnectTimeout(5 * 1000); //设置超时时间为5秒  
  58.         conn.setRequestMethod("POST");    
  59.         conn.setRequestProperty("Content-Type""application/soap+xml; charset=utf-8");  
  60.         conn.setRequestProperty("Content-Length", String.valueOf(data.length));  //设置长度  
  61.           
  62.         OutputStream outputStream = conn.getOutputStream();  
  63.         outputStream.write(data);  
  64.         outputStream.flush();  
  65.         outputStream.close();  
  66.           
  67.         if(conn.getResponseCode() == 200) {  
  68.             return parseResponseXML(conn.getInputStream());  //解析服务器端返回的数据  
  69.         }  
  70.           
  71.         return null;  
  72.     }  
  73.       
  74.     //解析返回的xml数据,并获得手机号归属地址  
  75.     private static String parseResponseXML(InputStream inputStream) throws XmlPullParserException, IOException {  
  76.         XmlPullParser parser = Xml.newPullParser();  
  77.         parser.setInput(inputStream, "UTF-8");  
  78.         int eventType = parser.getEventType();  //产生第一个事件  
  79.         while(eventType != XmlPullParser.END_DOCUMENT) {  //只要不是文档结束事件  
  80.             switch(eventType) {  
  81.             case XmlPullParser.START_TAG:   
  82.                 String name = parser.getName(); //获取解析器当前指向的元素的名称  
  83.                 if("getMobileCodeInfoResult".equals(name)) {  
  84.                     return parser.nextText();  
  85.                 }  
  86.                 break;  
  87.             }  
  88.             eventType = parser.next();  
  89.         }  
  90.         return null;  
  91.     }  
  92.       
  93. }  


6:StreamTool类的内容

[java]  view plain copy
  1. package com.capinfotech.mobile.utils;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6.   
  7. public class StreamTool {  
  8.   
  9.     /*  
  10.      * 从数据流中获得数据  
  11.      */    
  12.     public static  byte[] readInputStream(InputStream inputStream) throws IOException {    
  13.         byte[] buffer = new byte[1024];    
  14.         int len = 0;    
  15.         ByteArrayOutputStream bos = new ByteArrayOutputStream();    
  16.         while((len = inputStream.read(buffer)) != -1) {    
  17.             bos.write(buffer, 0, len);    
  18.         }    
  19.         bos.close();    
  20.         return bos.toByteArray();    
  21.             
  22.     }    
  23. }  


7:mobileaddress.xml的内容

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <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">  
  3.   <soap12:Body>  
  4.     <getMobileCodeInfo xmlns="http://WebXml.com.cn/">  
  5.       <mobileCode>$mobile</mobileCode>  
  6.       <userID></userID>  
  7.     </getMobileCodeInfo>  
  8.   </soap12:Body>  
  9. </soap12:Envelope>  


8:androidmanifest.xml的内容

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="com.capinfotech.mobileaddress"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  7.         <activity android:name=".MainActivity"  
  8.                   android:label="@string/app_name">  
  9.             <intent-filter>  
  10.                 <action android:name="android.intent.action.MAIN" />  
  11.                 <category android:name="android.intent.category.LAUNCHER" />  
  12.             </intent-filter>  
  13.         </activity>  
  14.   
  15.     </application>  
  16.     <uses-sdk android:minSdkVersion="8" />  
  17.     <uses-permission android:name="android.permission.INTERNET" />  
  18.   
  19. </manifest>   


9:程序运行效果图:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值