Android中调用WebService


一、将请求消息保存在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="NUM" />
 <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="look"
  />
 <TextView
              android:id="@+id/mobileAddress"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
  />
</LinearLayout>

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

 package test.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;

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

四、

C# WebServer 生成XML给android

android调用webservice实现图片上传

Android调用后台服务c# Webservice(源码)

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

generallizhong

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值