Android里实现号码归属地查询

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
	android:gravity="center_horizontal"
    >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:text="查询号码所在地"
        android:textSize="20sp"
        />

    <EditText
        android:id="@+id/et_querynum"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/please_input_querynumber" />

    <Button
        android:id="@+id/bt_query"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         android:textSize="20sp"
        android:text="查询" />

</LinearLayout>


MainActivity:

package cn.zyq.queryaddress;

import cn.zyq.queryaddress.service.QueryService;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	
	
	private Button bt_query;
	private EditText et_querynum;
	
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			String value = (String) msg.obj;
			Toast.makeText(MainActivity.this, value, Toast.LENGTH_LONG).show();
		}
		
	};
	/**
	 * 获得组件
	 */
	public void init(){
		bt_query = (Button) this.findViewById(R.id.bt_query);
		et_querynum = (EditText) this.findViewById(R.id.et_querynum);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		init();
		bt_query.setOnClickListener(this);
	}

	/**
	 * 点击时间,获取电话号码
	 */
	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		case R.id.bt_query:
			final String num = et_querynum.getText().toString().trim();			
			if(TextUtils.isEmpty(num)){
				Toast.makeText(this, "号码不能为空", Toast.LENGTH_SHORT).show();
			}
			//Android4.0以后,就不能在主线程中开启网络了,为了避免网络延迟造成界面假死的现象
			new Thread(){
				@Override
				public void run() {
					  String value = QueryService.getTel(num);
					  Message msg = new Message();
					  msg.obj = value;
					  handler.sendMessage(msg);
				}
			}.start();
			break;
		default:
			break;
		}
	}
}

服务类:

package cn.zyq.queryaddress.service;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

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

import android.util.Xml;

import cn.zyq.queryaddress.StringTool;

public class QueryService {

	public static String getTel(String num) {

		try {
			// 获取本地存储号码的xml格式文件
			InputStream in = QueryService.class.getClassLoader()
					.getResourceAsStream("post.xml");
			// 将流转换为字符串
			String conString = StringTool.inputstream2String(in);
			// 将电话号码替换占位符
			conString = conString.replace("$phonenum", num);
			// 得到由服务器返回的电话号码
			String res = sendPostMessage(conString);
			return res;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String sendPostMessage(String content) {
		URL url;
		String res;
		try {
			// 指定URL
			url = new URL(
					"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setConnectTimeout(5000);
			connection.setRequestMethod("POST");
			connection.setDoOutput(true);
			// 设定相应头
			connection.setRequestProperty("Content-Type",
					"text/xml; charset=utf-8");
			connection.setRequestProperty("Content-Length", content.length()
					+ "");
			// 写入服务器
			connection.getOutputStream().write(content.getBytes());
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				// 得到服务器返回的结果
				InputStream in = connection.getInputStream();
				// 用得到的流(实质为xml),解析到想要得到的数据--->电话号码
				res = getAddressInfo(in);
				return res;
			}
			return null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String getAddressInfo(InputStream in) throws Exception {

		try {
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(in, "utf-8");
			int eventType = parser.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT) {
				if ("getMobileCodeInfoResult".equals(parser.getName())) {
					return parser.nextText();
				}
				eventType = parser.next();
			}
			return "木有找到";
		} catch (XmlPullParserException e) {
			throw new RuntimeException(e);
		}

	}

}

工具类:
package cn.zyq.queryaddress;

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

public class StringTool {
	/**
	 * 将流转换为字符串
	 * @param in
	 * @return
	 * @throws Exception
	 */
	public static String inputstream2String(InputStream in) throws Exception{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int len = 0;
		byte [] buffer = new byte[1024];
		while((len = in.read(buffer))!=-1){
			bos.write(buffer, 0, len);
		}
		byte [] array = bos.toByteArray();
		String str = new String(array);
		return str;
	}

}

post.xml

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <getMobileCodeInfo xmlns="http://WebXml.com.cn/">
        <!-- 占位符 -->
      <mobileCode>$phonenum</mobileCode>
      
    </getMobileCodeInfo>
  </soap:Body>
</soap:Envelope>

运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值