你好,游客 登录 注册 搜索
背景:
阅读新闻

在Android中调用WebService【附源码】

[日期:2012-03-10] 来源:Linux社区  作者:coolszy [字体:大 中 小]

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

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

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

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

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

linux
本文评论   查看全部评论 (1)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款
第 1 楼
* 于工磊 发表于 2012/8/2 10:54:35
好的学习资料啊