Android 使用WebService

来源:互联网 发布:淘宝远望手机可靠吗 编辑:程序博客网 时间:2024/06/08 11:54
  最近在做Android项目要用到WebService就在网上搜索下,现在记录下来。

1:要用到Ksoap2-android jar包。下载地址:http://code.google.com/p/ksoap2-android/
2:把Jar引用到项目中。
3:编写代码
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"      android:paddingTop="5dip"      android:paddingLeft="5dip"      android:paddingRight="5dip"      >      <TextView          android:layout_width="fill_parent"           android:layout_height="wrap_content"           android:text="@string/numbers" />    <EditText android:id="@+id/phone_sec"          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:inputType="textPhonetic"          android:singleLine="true"          android:hint="@string/suchas" />    <Button android:id="@+id/query_btn"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_gravity="right"          android:text="@string/rearch" />    <TextView android:id="@+id/result_text"          android:layout_width="wrap_content"           android:layout_height="wrap_content"           android:layout_gravity="center_horizontal|center_vertical"      />  </LinearLayout> 

Mainactivity.java文件:

package com.wsclient.cn;import org.ksoap2.SoapEnvelope;import org.ksoap2.serialization.SoapObject;import org.ksoap2.serialization.SoapSerializationEnvelope;import org.ksoap2.transport.HttpTransportSE;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.support.v7.app.ActionBarActivity;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;public class MainActivity extends ActionBarActivity {    private EditText phoneSecEditText;      private TextView resultView;      private Button queryButton;     String phoneSec;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        phoneSecEditText = (EditText) findViewById(R.id.phone_sec);          resultView = (TextView) findViewById(R.id.result_text);          queryButton = (Button) findViewById(R.id.query_btn);        queryButton.setOnClickListener(new OnClickListener() {              @Override              public void onClick(View v) {                  // 手机号码(段)                  phoneSec = phoneSecEditText.getText().toString().trim();                  // 简单判断用户输入的手机号码(段)是否合法                  if ("".equals(phoneSec) || phoneSec.length() < 7) {                      // 给出错误提示                      phoneSecEditText.setError("您输入的手机号码(段)有误!");                      phoneSecEditText.requestFocus();                      // 将显示查询结果的TextView清空                      resultView.setText("");                      return;                  }                  Log.i("Thread","outof Thread");                new Thread(new Runnable() {                    @Override                    public void run() {                        Log.i("Thread","into Thread");                        // TODO Auto-generated method stub                        // 查询手机号码(段)信息                        getRemoteInfo(phoneSec);                        Message msg = handle.obtainMessage();                        msg.obj = result;                         handle.sendMessage(msg);                    }                }).start();            }          });            }    String result;    private Handler handle = new Handler(){        @Override        public void handleMessage(Message msg) {            // TODO Auto-generated method stub            super.handleMessage(msg);            Log.i("handle","into handle");            String result = msg.obj.toString();            Log.i("TAG",result);            // 将WebService返回的结果显示在TextView中            resultView.setText(result);        }    };    /**      * 手机号段归属地查询      *       * @param phoneSec 手机号段      */      public void getRemoteInfo(String phoneSec) {          // 命名空间          String nameSpace = "http://WebXml.com.cn/";          // 调用的方法名称          String methodName = "getMobileCodeInfo";        // EndPoint          String endPoint = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx";          // SOAP Action          String soapAction = "http://WebXml.com.cn/getMobileCodeInfo";         // 指定WebService的命名空间和调用的方法名          SoapObject rpc = new SoapObject(nameSpace, methodName);          // 设置需调用WebService接口需要传入的两个参数mobileCode、userId          rpc.addProperty("mobileCode", phoneSec);          rpc.addProperty("userId", "");          // 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本          SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);          envelope.bodyOut = rpc;        // 设置是否调用的是dotNet开发的WebService          envelope.dotNet = true;          // 等价于envelope.bodyOut = rpc;          envelope.setOutputSoapObject(rpc);        HttpTransportSE transport = new HttpTransportSE(endPoint);          try {              // 调用WebService              transport.call(soapAction, envelope);          } catch (Exception e) {              e.printStackTrace();          }          // 获取返回的数据          SoapObject object = (SoapObject) envelope.bodyIn;        Log.i("haha", (object==null) + "-------1");        result = object.getProperty(0).toString();//        if(object != null){//          Log.i("haha", (object.getProperty(0) == null) + "----2");//          // 获取返回的结果  //          String result = object.getProperty(0).toString();//          //          // 将WebService返回的结果显示在TextView中  //          resultView.setText(result);             //        }    }}

之前因为URL地址已经不能使用了,又重新在网上搜索新的地址。
WEB服务地址:http://www.webxml.com.cn/zh_cn/index.aspx
参考博客地址:
http://blog.csdn.net/lyq8479/article/details/6428288/
http://www.runoob.com/w3cnote/android-tutorial-webservice.html
第一个博客链接里面代码很完善了,第二个链接里面对WEB服务里面有的可以免费试用的服务介绍了很详细。

0 0
原创粉丝点击