Android 利用 Webservice 获取手机号码归属地

webservice地址:

http://www.webxml.com.cn/zh_cn/index.aspx
http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getMobileCodeInfo


其实了解webservice之后利用其获取服务很简单,无非就是按照例如下面图片发送相应内容到指定服务器,然后获取返回的内容进行相应处理就OK了。

下面给出了利用 Webservice 获取手机号码归属地的示例代码:

发送内容data.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>
下面为两个工具类,NumberParser.java:
package cn.itcast.login.util;

import java.io.InputStream;

import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

public class NumberParser {

	public static String getXmlInfo(InputStream is) throws Exception {
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(is, "utf-8");

		int type = parser.getEventType();
		while (type != XmlPullParser.END_DOCUMENT) {
			switch (type) {
			case XmlPullParser.START_TAG:
				if ("getMobileCodeInfoResult".equals(parser.getName())) {
					return parser.nextText();
				}
				break;
			}
			type = parser.next();
		}
		return "查无此号";
	}
}
StreamTool.java:
package cn.itcast.login.util;

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

public class StreamTool {
	/**
	 * 把一个inputstream里面的内容转化成一个byte[] 
	 */
	
	public static byte[] getBytes(InputStream is) throws Exception{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while((len = is.read(buffer))!=-1){
			bos.write(buffer, 0, len);
		}
		is.close();
		bos.flush();
		byte[] result = bos.toByteArray();
		/*System.out.println(new String(result));*/
		return  result;
	}
}
QueryService.java:
package service;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import cn.itcast.login.util.NumberParser;
import cn.itcast.login.util.StreamTool;

public class QueryService {
	/***
	 * 
	 * @param number
	 * @return
	 */
	public static String getAddress(String number) throws Exception {
		InputStream is = QueryService.class.getClassLoader()
				.getResourceAsStream("data.xml");
		byte[] data = StreamTool.getBytes(is);
		String xml = new String(data);
		System.out.println("aaaaaaa");
		String postxml = xml.replace("$mobile", number);
		System.out.println(postxml);
		return sendMessage(postxml);
	}

	public static String sendMessage(String postxml) throws Exception {

		URL url = new URL(
				"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getMobileCodeInfo");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		String data = postxml;

		conn.setRequestMethod("POST");
		conn.setConnectTimeout(5000);
		// 设置 http协议可以向服务器写数据
		conn.setDoOutput(true);
		// 设置http协议的消息头
		conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
		conn.setRequestProperty("Content-Length", data.length() + "");
		// 把我们准备好的data数据写给服务器
		OutputStream os = conn.getOutputStream();
		os.write(data.getBytes());
		// httpurlconnection 底层实现 outputstream 是一个缓冲输出流
		// 只要我们获取任何一个服务器返回的信息 , 数据就会被提交给服务器 , 得到服务器返回的流信息
		int code = conn.getResponseCode();
		System.out.println(code);
		if (code == 200) {
			InputStream is = conn.getInputStream();
			String address = NumberParser.getXmlInfo(is);
			return address;
		} else {
			return "访问网络出错";
		}
	}
}
DemoActivity
package cn.itcast.query;

import service.QueryService;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class DemoActivity extends Activity {
	/** Called when the activity is first created. */

	private EditText mEt;
	private Button mBt;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mEt = (EditText) this.findViewById(R.id.number);
		mBt = (Button) this.findViewById(R.id.bt_query);

	}

	public void query(View v) {
		String number = mEt.getText().toString().trim();
		try {
			String address = QueryService.getAddress(number);
			Toast.makeText(this, address, 1).show();
		} catch (Exception e) {
			Toast.makeText(this, "访问出错", 0).show();
			e.printStackTrace();
		}
	}
}
布局文件main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <EditText
        android:id="@+id/number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="15538311981" >
    </EditText>

    <Button
        android:id="@+id/bt_query"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="query"
        android:text="@string/query" />

</LinearLayout>
运行结果截图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值