您的位置:首页 > 移动开发 > Android开发

Android手机归属地查询工具

2015-10-28 09:22 495 查看


Android手机归属地查询工具

在Android应用开发中,经常需要与网络上的服务端的程序(J2EE或者.NET等应用)进行通信、交互。例如“优酷、土豆”的android客户端,每天访问都会有最新的视频资讯,那些是哪里来的呢?如果你正在从事企业级开发,你们公司的CRM系统需要开发一个Android手机移动版本,方便随时随地联系、关怀客户。那android客户端上需要显示的客户列表和基本信息那些从哪里来呢?当然,公司可以让每个人打开电脑,对着屏幕上的CRM系统,不停的往自己手机里面去录入,然后一条条存起来。(很显然没人会这么干)
更为“明智”的一种方式是:公司的CRM系统提供一个webservice接口,android客户端去访问,读取到数据后,然后存入SqlLite数据库中(这是其中一种存储方式),定期更新并同步数据。这样省去了不少人力和时间,也保证了数据的正确性,实时性。
那在android开发中,如何访问网络上webservice呢?本文将通过一个“手机归属地查询工具”实例的方式,向大家详细介绍,在android中如何调用远程服务器端提供的webservice,实现典型的移动互联网分布式应用。有些软件厂商和作者总喜欢“故作神秘”,将这种分布式的应用称之为所谓的“云计算”。真是浮云啊!
第一步
上网google到一个可靠并且免费的webservice地址。推荐一个网站:http://www.webxml.com.cn/zh_cn/index.aspx
找到了“天气预报”的服务公开地址为:http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx
好吧。先在浏览器中访问该地址,输入自己的手机号码测试一下,看是否可靠。
调用http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getMobileCodeInfo,观察SOAP消息规范。



关于什么是WebService?[b]WebService的原理、SOAP消息等等方面的知识,不是本文讨论的重点,请参阅博客园其他文章。[/b]
我们需要的是请求webservice,获取服务响应的数据,解析后并显示。首先,将服务公布的SOAP请求消息保存在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>


下一步:建立项目,并完成基本的软件界面布局。文件如下:

<?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:text="@string/button"
android:id="@+id/button"
/>

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/address"
/>
</LinearLayout>


接下来正式开始编码了,接收用户输入,给界面上的按钮设置事件,完成界面数据显示及用户提示等。

package cn.itcast.mobile.address;

import java.io.InputStream;

import cn.itcast.service.MobileInfoService;
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 EditText mobileText;
private TextView addressView;
private static final String TAG = "MainActivity";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mobileText = (EditText)this.findViewById(R.id.mobile);
addressView = (TextView)this.findViewById(R.id.address);
Button button = (Button)this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String mobile = mobileText.getText().toString();
InputStream inStream = this.getClass().getClassLoader().getResourceAsStream("mobilesoap.xml");
try {
addressView.setText(MobileInfoService.getMobileAddress(inStream, mobile));
} catch (Exception e) {
Log.e(TAG, e.toString());
Toast.makeText(MainActivity.this, "查询失败", 1).show();
}
}
});
}
}


下面的代码,才是重点(包含http网络编程,XML编程等)。
主要步骤就是读取SOAP消息XML文件,动态替换soap参数,发送http响应,等待服务端响应,解析服务端响应的数据,返回给Activity去完成页面显示/提示。

package cn.itcast.service;

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 android.util.Xml;
import cn.itcast.utils.StreamTool;

public class MobileInfoService {

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 = "\\{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.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;
}
}


最后提醒大家一句,记得在项目清单文件中,加入网络访问权限,否则无法访问公网。(笔者就因为一时大意,弄了一身汗,还好有Android单元调试和日志控制台比较方便,严重推荐大家使用)。

<!-- 访问网络的权限 -->
<uses-permission android:name="android.permission.INTERNET"/>


好了,通过上面简单的例子,相信读者已经明白了webservice的调用方式。效果图我就不贴了,读者不妨动手去实践吧。
更多Android系列文章,请访问http://blog.csdn.net/dinglang_2009/article/category/887633
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: