[转帖]在Android中调用WebService ._Android, Python及开发编程讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  Android, Python及开发编程讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 3875 | 回复: 0   主题: [转帖]在Android中调用WebService .        下一篇 
q563725885
注册用户
等级:少校
经验:1134
发帖:98
精华:1
注册:2013-5-7
状态:离线
发送短消息息给q563725885 加好友    发送短消息息给q563725885 发消息
发表于: IP:您无权察看 2013-5-7 18:16:19 | [全部帖] [楼主帖] 楼主

某些情况下我们可能需要与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
[html]view plaincopyprint?

  1. <SPAN style="FONT-SIZE: 16px"><?xml version="1.0" encoding="utf-8"?>  
  2. <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">  
  3.   <soap12:Body>  
  4.     <getMobileCodeInfo xmlns="http://WebXml.com.cn/">  
  5.       <mobileCode>$mobile</mobileCode>  
  6.       <userID></userID>  
  7.     </getMobileCodeInfo>  
  8.   </soap12:Body>  
  9. </soap12:Envelope></SPAN>  


<?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
[html]view plaincopyprint?

  1. <SPAN style="FONT-SIZE: 16px"><?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:orientation="vertical"  
  5.     android:layout_width="fill_parent"  
  6.     android:layout_height="fill_parent">  
  7.     <TextView  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="手机号码" />  
  11.     <EditText  
  12.         android:id="@+id/mobileNum"   
  13.         android:layout_width="fill_parent"  
  14.         android:layout_height="wrap_content"  
  15.         android:text=""  
  16.         />  
  17.     <Button  
  18.         android:id="@+id/btnSearch"  
  19.         android:layout_width="wrap_content"  
  20.         android:layout_height="wrap_content"  
  21.         android:text="查询"  
  22.         />  
  23.     <TextView  
  24.         android:id="@+id/mobileAddress"  
  25.         android:layout_width="fill_parent"  
  26.         android:layout_height="wrap_content"  
  27.         />  
  28. </LinearLayout></SPAN>  

<?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,获取服务响应的数据,解析后并显示。

[java]view plaincopyprint?

  1. <SPAN style="FONT-SIZE: 16px">package com.szy.webservice; 
  2. import java.io.ByteArrayOutputStream; 
  3. import java.io.InputStream; 
  4. import java.io.OutputStream; 
  5. import java.net.HttpURLConnection; 
  6. import java.net.URL; 
  7. import java.util.HashMap; 
  8. import java.util.Map; 
  9. import java.util.regex.Matcher; 
  10. import java.util.regex.Pattern; 
  11. import org.xmlpull.v1.XmlPullParser; 
  12. import android.app.Activity; 
  13. import android.os.Bundle; 
  14. import android.util.Log; 
  15. import android.util.Xml; 
  16. import android.view.View; 
  17. import android.widget.Button; 
  18. import android.widget.EditText; 
  19. import android.widget.TextView; 
  20. import android.widget.Toast; 
  21. /** 
  22.  * @author coolszy 
  23.  * @date 2012-3-8 
  24.  * @blog http://blog.92coding.com 
  25.  */ 
  26. public class MainActivity extends Activity 
  27.        private EditText mobileNum; 
  28.        private TextView mobileAddress; 
  29.        private static final String TAG = "MainActivity"; 
  30.       
  31.       
  32.        @Override 
  33.        public void onCreate(Bundle savedInstanceState) 
  34.        { 
  35.              super.onCreate(savedInstanceState); 
  36.              setContentView(R.layout.main); 
  37.             
  38.             
  39.              mobileNum = (EditText) this.findViewById(R.id.mobileNum); 
  40.              mobileAddress = (TextView) this.findViewById(R.id.mobileAddress); 
  41.              Button btnSearch = (Button) this.findViewById(R.id.btnSearch); 
  42.              btnSearch.setOnClickListener(new View.OnClickListener() 
  43.              { 
  44.                    @Override 
  45.                    public void onClick(View v) 
  46.                    { 
  47.                          // 获取电话号码 
  48.                          String mobile = mobileNum.getText().toString(); 
  49.                          // 读取xml文件 
  50.                          InputStream inStream = this.getClass().getClassLoader().getResourceAsStream("mobilesoap.xml"); 
  51.                          try 
  52.                          { 
  53.                                // 显示电话号码地理位置,该段代码不合理,仅供参考 
  54.                                mobileAddress.setText(getMobileAddress(inStream, mobile)); 
  55.                          } catch (Exception e) 
  56.                          { 
  57.                                Log.e(TAG, e.toString()); 
  58.                                Toast.makeText(MainActivity.this, "查询失败", 1).show(); 
  59.                          } 
  60.                    } 
  61.              }); 
  62.        } 
  63.       
  64.       
  65.        /** 
  66.        * 获取电话号码地理位置 
  67.        * 
  68.        * @param inStream 
  69.        * @param mobile 
  70.        * @return 
  71.        * @throws Exception 
  72.        */ 
  73.        private String getMobileAddress(InputStream inStream, String mobile) throws Exception 
  74.        { 
  75.              // 替换xml文件中的电话号码 
  76.              String soap = readSoapFile(inStream, mobile); 
  77.              byte[] data = soap.getBytes(); 
  78.              // 提交Post请求 
  79.              URL url = new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx"); 
  80.              HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
  81.              conn.setRequestMethod("POST"); 
  82.              conn.setConnectTimeout(5 * 1000); 
  83.              conn.setDoOutput(true); 
  84.              conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8"); 
  85.              conn.setRequestProperty("Content-Length", String.valueOf(data.length)); 
  86.              OutputStream outStream = conn.getOutputStream(); 
  87.              outStream.write(data); 
  88.              outStream.flush(); 
  89.              outStream.close(); 
  90.              if (conn.getResponseCode() == 200) 
  91.              { 
  92.                    // 解析返回信息 
  93.                    return parseResponseXML(conn.getInputStream()); 
  94.              } 
  95.              return "Error"; 
  96.        } 
  97.       
  98.       
  99.        private String readSoapFile(InputStream inStream, String mobile) throws Exception 
  100.        { 
  101.              // 从流中获取文件信息 
  102.              byte[] data = readInputStream(inStream); 
  103.              String soapxml = new String(data); 
  104.              // 占位符参数 
  105.              Map<String, String> params = new HashMap<String, String>(); 
  106.              params.put("mobile", mobile); 
  107.              // 替换文件中占位符 
  108.              return replace(soapxml, params); 
  109.        } 
  110.       
  111.       
  112.        /** 
  113.        * 读取流信息 
  114.        * 
  115.        * @param inputStream 
  116.        * @return 
  117.        * @throws Exception 
  118.        */ 
  119.        private byte[] readInputStream(InputStream inputStream) throws Exception 
  120.        { 
  121.              byte[] buffer = new byte[1024]; 
  122.              int len = -1; 
  123.              ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); 
  124.              while ((len = inputStream.read(buffer)) != -1) 
  125.              { 
  126.                    outSteam.write(buffer, 0, len); 
  127.              } 
  128.              outSteam.close(); 
  129.              inputStream.close(); 
  130.              return outSteam.toByteArray(); 
  131.        } 
  132.       
  133.       
  134.        /** 
  135.        * 替换文件中占位符 
  136.        * 
  137.        * @param xml 
  138.        * @param params 
  139.        * @return 
  140.        * @throws Exception 
  141.        */ 
  142.        private String replace(String xml, Map<String, String> params) throws Exception 
  143.        { 
  144.              String result = xml; 
  145.              if (params != null && !params.isEmpty()) 
  146.              { 
  147.                    for (Map.Entry<String, String> entry : params.entrySet()) 
  148.                    { 
  149.                          String name = "\\$" + entry.getKey(); 
  150.                          Pattern pattern = Pattern.compile(name); 
  151.                          Matcher matcher = pattern.matcher(result); 
  152.                          if (matcher.find()) 
  153.                          { 
  154.                                result = matcher.replaceAll(entry.getValue()); 
  155.                          } 
  156.                    } 
  157.              } 
  158.              return result; 
  159.        } 
  160.       
  161.       
  162.        /** 
  163.        * 解析XML文件 
  164.        * @param inStream 
  165.        * @return 
  166.        * @throws Exception 
  167.        */ 
  168.        private static String parseResponseXML(InputStream inStream) throws Exception 
  169.        { 
  170.              XmlPullParser parser = Xml.newPullParser(); 
  171.              parser.setInput(inStream, "UTF-8"); 
  172.              int eventType = parser.getEventType();// 产生第一个事件 
  173.              while (eventType != XmlPullParser.END_DOCUMENT) 
  174.              { 
  175.                    // 只要不是文档结束事件 
  176.                    switch (eventType) 
  177.                    { 
  178.                          case XmlPullParser.START_TAG: 
  179.                          String name = parser.getName();// 获取解析器当前指向的元素的名称 
  180.                          if ("getMobileCodeInfoResult".equals(name)) 
  181.                          { 
  182.                                return parser.nextText(); 
  183.                          } 
  184.                          break; 
  185.                    } 
  186.                    eventType = parser.next(); 
  187.              } 
  188.              return null; 
  189.        } 
  190. }</SPAN> 


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;
       }
}

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

[html]view plaincopyprint?

  1. <SPAN style="FONT-SIZE: 16px"><uses-permission android:name="android.permission.INTERNET"/></SPAN>  


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

;

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

北京联动北方科技有限公司

实例代码:http://115.com/file/anjh65a6




赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论