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

1:原理解析

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

 

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

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>


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

 

服务器端返回的信息:

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>


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

                                                                                                   android代码

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

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">手机号归属地查询</string>
    <string name="mobile">手机号</string>
    <string name="button">查询</string>
    <string name="show">在此显示查询结果</string>
</resources>

 

3:布局文件main.xml

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/mobile"
    />
    <EditText 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/mobile"
    />
    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/button"
     android:text="@string/button"
    />
    <TextView
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/address"
     android:text="@string/show"
    />
</LinearLayout>

4:MainActivity的内容

package com.capinfotech.mobileaddress;

import java.io.InputStream;

import com.capinfotech.mobile.service.MobileService;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private static final String TAG = "MainActivity";
	private EditText mobileEditText = null;  //输入的查询手机号
	private Button addressButton = null;     //查询按钮
	private TextView addressResult = null;   //显示查询的地址
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mobileEditText = (EditText)findViewById(R.id.mobile);
        addressButton = (Button)findViewById(R.id.button);
        addressResult = (TextView)findViewById(R.id.address);
        
        addressButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String mobile = mobileEditText.getText().toString();
				InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("mobileaddress.xml");
				Log.i(TAG, "inputStream: " + (inputStream == null));
				
				try {
					Log.i(TAG, "inputStream: " + inputStream.available());
					String address = MobileService.getMobileAddress(inputStream, mobile);
					Log.i(TAG, "address: " + address);
					addressResult.setText(address);
				} catch(Exception e) {
					Log.e(TAG, e.toString());
					Toast.makeText(MainActivity.this, "网络异常", Toast.LENGTH_LONG).show();
				}
			}
		});
    }
}


5:MobileService类的内容

 

package com.capinfotech.mobile.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.capinfotech.mobile.utils.StreamTool;

import android.util.Log;
import android.util.Xml;

public class MobileService {
	private static final String TAG = "MobileService";
	//根据inputStream和mobile(用户输入的手机号)来对文件mobileaddress.xml的mobile进行替换
	public static String readSoapFile(InputStream inputStream, String mobile) throws Exception {
		byte[] data = StreamTool.readInputStream(inputStream);
		Log.i(TAG, "datalength: " + data.length);
		String soapxml = new String(data);
		Log.i(TAG, "soapxml: " + soapxml);
		Map<String, String> params = new HashMap<String, String>();
		params.put("mobile", mobile);
		return replace(soapxml, params);
	
	}
	
	//完成替换的函数
	private 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 = "\\{1}quot; + entry.getKey();
				Pattern pattern = Pattern.compile(name);
				Matcher matcher = pattern.matcher(result);
			    if(matcher.find()) {
			    	result = matcher.replaceAll(entry.getValue());
			    }
			}
		}
		return result;
	}
	
	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.setDoOutput(true);  //设置允许输出
		conn.setConnectTimeout(5 * 1000); //设置超时时间为5秒
		conn.setRequestMethod("POST");  
		conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
		conn.setRequestProperty("Content-Length", String.valueOf(data.length));  //设置长度
		
		OutputStream outputStream = conn.getOutputStream();
		outputStream.write(data);
		outputStream.flush();
		outputStream.close();
		
		if(conn.getResponseCode() == 200) {
			return parseResponseXML(conn.getInputStream());  //解析服务器端返回的数据
		}
		
		return null;
	}
	
	//解析返回的xml数据,并获得手机号归属地址
	private static String parseResponseXML(InputStream inputStream) throws XmlPullParserException, IOException {
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(inputStream, "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;
	}
	
}


6:StreamTool类的内容

package com.capinfotech.mobile.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class StreamTool {

	/* 
     * 从数据流中获得数据 
     */  
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {  
        byte[] buffer = new byte[1024];  
        int len = 0;  
        ByteArrayOutputStream bos = new ByteArrayOutputStream();  
        while((len = inputStream.read(buffer)) != -1) {  
            bos.write(buffer, 0, len);  
        }  
        bos.close();  
        return bos.toByteArray();  
          
    }  
}


7:mobileaddress.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>


8:androidmanifest.xml的内容

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.capinfotech.mobileaddress"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.INTERNET" />

</manifest> 


9:程序运行效果图:

 

 

如果大家需要源代码的话,到我的资源下下载吧


 

 

 

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

波哥的技术积累

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值