在Android中调用WebService实例

作者:coolszy 时间:2023-10-27 12:00:10 

某些情况下我们可能需要与Mysql或者Oracle数据库进行数据交互,有些朋友的第一反应就是直接在Android中加载驱动然后进行数据的增删改查。我个人不推荐这种做法,一是手机毕竟不是电脑,操作大量数据费时费电;二是流量贵如金那。我个人比较推荐的做法是使用Java或PHP等开发接口或者编写WebService进行数据库的增删该查,然后Android调用接口或者WebService进行数据的交互。本文就给大家讲解在Android中如何调用远程服务器端提供的WebService。

既然是调用WebService,我们首先的搭建WebService服务器。

下面演示的就是如何通过该网站提供的手机号码归属地查询WebService服务查询号码归属地

调用地址http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getMobileCodeInfo。

首先,将请求消息保存在XML文件中,然后使用$替换请求参数,如下:

mobilesoap.xml


<span style="font-size:16px;"><?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></span>

  其次,设计MainActivity布局文件,
main.xml


<span style="font-size:16px;"><?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></span>

 下面贴出MainActivity,

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


<span style="font-size:16px;">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;
 }
}</span>

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


<span style="font-size:16px;"><uses-permission android:name="android.permission.INTERNET"/></span>

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

标签:webservice,调用
0
投稿

猜你喜欢

  • Spring Boot示例分析讲解自动化装配机制核心注解

    2022-07-26 15:56:14
  • Android控件CardView实现卡片效果

    2023-09-05 17:01:16
  • c# Newtonsoft 六个值得使用的特性(下)

    2022-02-18 11:38:32
  • Android AutoCompleteTextView连接数据库自动提示的方法(附demo源码下载)

    2023-09-23 14:53:20
  • C# 设计模式系列教程-简单工厂模式

    2023-10-31 13:49:29
  • C# 8.0可空引用类型的使用注意记录

    2022-10-03 23:29:40
  • SpringBoot上传图片到指定位置并返回URL的实现

    2023-08-13 14:02:52
  • Android实现View滑动效果的6种方法

    2023-01-29 15:12:19
  • Spring boot Mybatis 整合(完整版)

    2023-03-28 17:14:32
  • SpringBoot整合BCrypt实现密码加密

    2021-12-09 20:01:08
  • java启动线程的3种方式对比分析

    2023-12-17 08:38:41
  • Java框架---Spring详解

    2021-07-09 14:27:30
  • 基于OpenCv与JVM实现加载保存图像功能(JAVA 图像处理)

    2021-12-27 23:09:33
  • mybatis源码解读-Java中executor包的语句处理功能

    2023-09-03 06:34:16
  • Android显示富文本+夜间深色模式

    2023-11-11 12:33:59
  • Android之FanLayout制作圆弧滑动效果

    2023-01-14 16:58:29
  • 快速了解hibernate配置文件与映射文件

    2023-11-04 23:02:26
  • Java实现天天酷跑小游戏完整代码(附源码)

    2021-08-03 09:43:43
  • Springboot实现给前端返回一个tree结构方法

    2022-04-02 23:37:07
  • ListView滑动隐藏显示ToolBar的实例

    2022-09-15 23:15:52
  • asp之家 软件编程 m.aspxhome.com