某些情况下我们可能需要与Mysql或者Oracle数据库进行数据交互,有些朋友的第一反应就是直接在Android中加载驱动然后进行数据的增删改查。我个人不推荐这种做法,一是手机毕竟不是电脑,操作大量数据费时费电;二是流量贵如金那。我个人比较推荐的做法是使用Java或PHP等开发接口或者编写WebService进行数据库的增删该查,然后Android调用接口或者WebService进行数据的交互。本文就给大家讲解在Android中如何调用远程服务器端提供的WebService。
既然是调用WebService,我们首先的搭建WebService服务器。为了便于操作,我们就使用网上免费的WebService进行学习。
地址:http://www.webxml.com.cn/zh_cn/index.aspx
下面演示的就是如何通过该网站提供的手机号码归属地查询WebService服务查询号码归属地
调用地址http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getMobileCodeInfo。
首先,将请求消息保存在XML文件中,然后使用$替换请求参数,如下:
mobilesoap.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>

其次,设计MainActivity布局文件,
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="手机号码" />
<EditText
android:id="@+id/mobileNum"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
/>
<Button
android:id="@+id/btnSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="查询"
/>
<TextView
android:id="@+id/mobileAddress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

下面贴出MainActivity,
在Android中调用WebService还是比较简单的:请求webservice,获取服务响应的数据,解析后并显示。

 package com.szy.webservice;

 import java.io.ByteArrayOutputStream;
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.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast; /**
* @author coolszy
* @date 2012-3-8
* @blog http://blog.92coding.com
*/
public class MainActivity extends Activity
{
private EditText mobileNum;
private TextView mobileAddress;
private static final String TAG = "MainActivity"; @Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main); mobileNum = (EditText) this.findViewById(R.id.mobileNum);
mobileAddress = (TextView) this.findViewById(R.id.mobileAddress);
Button btnSearch = (Button) this.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// 获取电话号码
String mobile = mobileNum.getText().toString();
// 读取xml文件
InputStream inStream = this.getClass().getClassLoader().getResourceAsStream("mobilesoap.xml");
try
{
// 显示电话号码地理位置,该段代码不合理,仅供参考
mobileAddress.setText(getMobileAddress(inStream, mobile));
} catch (Exception e)
{
Log.e(TAG, e.toString());
Toast.makeText(MainActivity.this, "查询失败", 1).show();
}
}
});
} /**
* 获取电话号码地理位置
*
* @param inStream
* @param mobile
* @return
* @throws Exception
*/
private String getMobileAddress(InputStream inStream, String mobile) throws Exception
{
// 替换xml文件中的电话号码
String soap = readSoapFile(inStream, mobile);
byte[] data = soap.getBytes();
// 提交Post请求
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);
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 "Error";
} private String readSoapFile(InputStream inStream, String mobile) throws Exception
{
// 从流中获取文件信息
byte[] data = readInputStream(inStream);
String soapxml = new String(data);
// 占位符参数
Map<String, String> params = new HashMap<String, String>();
params.put("mobile", mobile);
// 替换文件中占位符
return replace(soapxml, params);
} /**
* 读取流信息
*
* @param inputStream
* @return
* @throws Exception
*/
private byte[] readInputStream(InputStream inputStream) throws Exception
{
byte[] buffer = new byte[1024];
int len = -1;
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1)
{
outSteam.write(buffer, 0, len);
}
outSteam.close();
inputStream.close();
return outSteam.toByteArray();
} /**
* 替换文件中占位符
*
* @param xml
* @param params
* @return
* @throws Exception
*/
private 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 = "\\$" + entry.getKey();
Pattern pattern = Pattern.compile(name);
Matcher matcher = pattern.matcher(result);
if (matcher.find())
{
result = matcher.replaceAll(entry.getValue());
}
}
}
return result;
} /**
* 解析XML文件
* @param inStream
* @return
* @throws Exception
*/
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;
}
}

最后注意,由于需要访问网络,需要加上权限

<uses-permission android:name="android.permission.INTERNET"/>

通过上面简单的例子,相信大家已经学习了如何在Android中调用WebService,最后运行效果:

在Android中调用WebService的更多相关文章

  1. 转--Android中调用webservice的工具类

    最近学习WebService,感觉利用这个借口开发网站的Android客户端方便及了,用到一个工具类,这里铭记一下. public static final String WebServiceName ...

  2. 在Android中调用C#写的WebService(附源代码)

    由于项目中要使用Android调用C#写的WebService,于是便有了这篇文章.在学习的过程中,发现在C#中直接调用WebService方便得多,直接添加一个引用,便可以直接使用将WebServi ...

  3. 在Android中使用Android Ksoap2调用WebService

    一.WebService介绍 WebService是基于SOAP协议可实现web服务器与web服务器之间的通信,因采用SOAP协议传送XML数据具有平台无关性,也是成为解决异构平台之间通信的重要解决方 ...

  4. 【转】Android 学习笔记——利用JNI技术在Android中调用、调试C++代码

    原文网址:http://cherishlc.iteye.com/blog/1756762 在Android中调用C++其实就是在Java中调用C++代码,只是在windows下编译生成DLL,在And ...

  5. android之调用webservice 实现图片上传

    转:http://www.cnblogs.com/top5/archive/2012/02/16/2354517.html public void testUpload(){ try{ String ...

  6. Android中调用C++函数的一个简单Demo

    这里我不想多解释什么,对于什么JNI和NDK的相关内容大家自己去百度或谷歌.我对Android的学习也只是个新手.废话少说直接进入正题. 一.在Eclipse中创建一个Android Applicat ...

  7. Java乔晓松-android中调用系统拍照功能并显示拍照的图片

    android中调用系统拍照功能并显示拍照的图片 如果你是拍照完,利用onActivityResult获取data数据,把data数据转换成Bitmap数据,这样获取到的图片,是拍照的照片的缩略图 代 ...

  8. 存储过程中调用webservice

    存储过程中调用webservice其实是在数据库中利用系统函数调用OLE. 1.查找webservice api 可得到MSSOAP.SoapClient. 2.查找API 接口可得到mssoapin ...

  9. Android 中调用本地命令

    Android 中调用本地命令 通常来说,在 Android 中调用本地的命令的话,一般有以下 3 种情况: 调用下也就得了,不管输出的信息,比如:echo Hello World.通常来说,这种命令 ...

随机推荐

  1. Largest Rectangle in a Histogram(DP)

    Largest Rectangle in a Histogram Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K ...

  2. iOS图片如何按比例显示

    文/罚难(简书作者)原文链接:http://www.jianshu.com/p/ec7d3f210983著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”. 只需加这么一段代码,如下: im ...

  3. Knockoutjs 实践入门 (3) 绑定数组

    <form id="form1" runat="server">        <div>            <!--text ...

  4. [.NET领域驱动设计实战系列]专题九:DDD案例:网上书店AOP和站点地图的实现

    一.引言 在前面一专题介绍到,要让缓存生效还需要实现对AOP(面向切面编程)的支持.所以本专题将介绍了网上书店案例中AOP的实现.关于AOP的概念,大家可以参考文章:http://www.cnblog ...

  5. 终于解决:升级至.NET 4.6.1后VS2015生成WCF客户端代理类的问题

    在Visual Studio 2015中将一个包含WCF引用的项目的targetFramework从4.5改为4.6.1的时候,VS2015会重新生成WCF客户端代理类.如果WCF引用配置中选中了&q ...

  6. note of introduction of Algorithms(Lecture 3 - Part1)

    Lecture 3(part 1) Divide and conquer 1. the general paradim of algrithm as bellow: 1. divide the pro ...

  7. UWP开发随笔——使用SQLite数据库

    摘要 大多数的app都需要数据存储,在数据存储这方面,强大的windows把app数据分为两种:settings和files,并提供了十分简洁的api,让开发者能够轻松使用.但是在有些场景下,app的 ...

  8. 设计模式之美:Visitor(访问者)

    索引 意图 结构 参与者 适用性 效果 相关模式 实现 实现方式(一):Visitor 模式结构样式代码. 实现方式(二):使用 Visitor 模式解构设计. 实现方式(三):使用 Acyclic ...

  9. 使用ACE_Task管理线程

    为什么要使用ACE_Task来管理线程 从C#转到C++后,感觉到C++比C#最难的地方,就是在系统编程时,C#中有对应的类库,我接触到一个类后,就可以通过这个类,知道很多相关的功能.而在C++中,必 ...

  10. Git学习笔记(9)——自定义配置

    本文主要记录了Git的一些易用化的配置和别名的使用 配置Git的命令输出带有颜色,更加醒目 //配置输出颜色 $ git config --global color.ui true //取消输出颜色 ...