Android中调用webservice

来源:互联网 发布:php代码在线测试 编辑:程序博客网 时间:2024/04/30 08:25
调用 WebService 分以下几步:

  1、指定 WebService 的命名空间和调用方法;

  2、设置调用方法的参数值,如果没有参数,可以省略,设置方法的参数值的代码如下:
  rpc.addProperty("abc", "test");

  要注意的是,addProperty方法的第1个参数虽然表示调用方法的参数名,但该参数值并不一定与服务端的WebService类中的方法参数名一致,只要设置参数的顺序一致即可。

  3、生成调用Webservice方法的SOAP请求信息。
  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
  envelope.bodyOut = rpc;
  envelope.dotNet = false; //这里如果设置为TRUE,那么在服务器端将获取不到参数值(如:将这些数据插入到数据库中的话)
  envelope.setOutputSoapObject(rpc);
  创建SoapSerializationEnvelope对象时需要通过SoapSerializationEnvelope类的构造方法设置SOAP协议的版本号。
  该版本号需要根据服务端WebService的版本号设置。
  在创建SoapSerializationEnvelope对象后,不要忘了设置SOAPSoapSerializationEnvelope类的bodyOut属性, 该属性的值就是在第一步创建的SoapObject对象。

  4、创建HttpTransportsSE对象。
  这里不要使用 AndroidHttpTransport ht = new AndroidHttpTransport(URL); 这是一个要过期的类
  private static String URL = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
  HttpTransportSE ht = new HttpTransportSE(URL);
  ht.debug = true;

  5、使用call方法调用WebService方法
  private static String SOAP_ACTION = "http://WebXml.com.cn/getWeatherbyCityName";
  ht.call(SOAP_ACTION, envelope);

  6、获得WebService方法的返回结果
  有两种方法:
  (1)、使用getResponse方法获得返回数据。
  (2)、使用 bodyIn 及 getProperty。

  7、 这时候执行会出错,提示没有权限访问网络
  需要修改 AndroidManifest.xml 文件,赋予相应权限
  简单来说就是增加下面这行配置:<uses-permission android:name="android.permission.INTERNET"></uses-permission>

 

import java.util.ArrayList;   
import java.util.HashMap;   
import java.util.Iterator;   
import java.util.List;   
import java.util.Map;   
import java.util.Map.Entry;   
  
import org.ksoap2.SoapEnvelope;   
import org.ksoap2.serialization.SoapObject;   
import org.ksoap2.serialization.SoapPrimitive;   
import org.ksoap2.serialization.SoapSerializationEnvelope;   
import org.ksoap2.transport.HttpTransportSE; 
  
import android.app.Activity;   
import android.app.ProgressDialog;   
import android.os.Bundle;   
import android.os.Handler;   
import android.os.Message;   
import android.view.View;   
import android.view.View.OnClickListener;   
import android.widget.Button;   
import android.widget.EditText;   
import android.widget.ListView;   
import android.widget.SimpleAdapter;   
  
public class MainActivity extends Activity {   
        //显示结果的listview   
        ListView listView=null;   
        //输入文本框   
        EditText provinceEdit=null;   
        //用于存放数据的集合list   
        List<Map<String, Object>> data=null;   
        //提示对话框   
        ProgressDialog myDialog=null;   
        //搜索按钮   
        Button searchButton=null;   
           
    /** Called when the activity is first created. */  
    @Override  
    public void onCreate(Bundle savedInstanceState) {   
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.main);   
        //获得文本输入框   
        provinceEdit=(EditText) this.findViewById(R.id.provinceEdit);   
        //获得搜索按钮   
        searchButton=(Button) this.findViewById(R.id.searchButton);   
        //为搜索按钮添加单击监听事件   
        searchButton.setOnClickListener(new OnClickListener(){   
  
                        public void onClick(View v) {   
                                //响应按钮单击事件的函数   
                                ResponseOnClick();   
                                   
                        }   
                   
        });   
    }   
       
    //响应按钮单击事件的函数   
   public  void  ResponseOnClick(){   
              
            //创建一个线程   
           HttpThread thread=new HttpThread(handler);   
              
           //构造请求参数   
           HashMap <String ,Object> params=new HashMap<String ,Object>();   
           try{   
                   CharSequence etValue=provinceEdit.getText();   
                   String name="";   
                   if(etValue!=null){   
                           //字符转码   
                            name=new String(etValue.toString().getBytes(),"UTF-8");   
                               
                   }   
                   params.put("byProvinceName", name);   
           }catch(Exception ex){   
                   ex.printStackTrace();   
           }   
              
           //   
           String url="http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx";   
          // String url = "http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx";      
       String nameSpace = "http://WebXml.com.cn/";      
       String methodName = "getSupportCity";      
       // 开始新线程进行WebService请求      
       thread.doStart(url, nameSpace, methodName, params);      
              
    }   
   /**  
    * 捕获消息队列  
    *   
    */  
   Handler handler=new Handler(){   
              
         public void handleMessage(Message m){   
                 ArrayList <String> myList=(ArrayList<String>)m.getData().getStringArrayList("data");   
                    
                 if(myList !=null){   
                         if(data !=null){   
                                 data.clear();   
                         }else{   
                                 data=new ArrayList<Map <String, Object>>();   
                         }   
                            
                         for(int i=0;i<myList.size();i++){   
                                 Map<String, Object> item=new HashMap<String, Object>();   
                                 item.put("text", myList.get(i));   
                                 data.add(item);   
                         }   
                            
                         /**  
                          * 列表显示  
                          *   
                          */  
                         SimpleAdapter simpleAdapter=new SimpleAdapter(MainActivity.this  
                        ,data,R.layout.listlayout,new String[] {"text"},new int []{R.id.showData});   
                         listView=(ListView) findViewById(R.id.showListView);   
                         listView.setAdapter(simpleAdapter);   
                 }   
         }     
   };   
  /**  
   * 线程类  
   * @author Administrator  
   *  
   */  
      
   public class HttpThread extends Thread{   
           private Handler handle=null;   
           String url=null;   
           String nameSpace=null;   
           String methodName=null;   
           HashMap <String ,Object> params=null;   
           ProgressDialog progressDialog=null;   
              
           //构造函数   
           public HttpThread(Handler hander){   
                   handle=hander;   
           }   
              
           /**  
            * 启动线程  
            */  
           public void doStart(String url, String nameSpace, String methodName,   
                                HashMap<String, Object> params) {   
                        // TODO Auto-generated method stub   
                   this.url=url;   
                   this.nameSpace=nameSpace;   
                   this.methodName=methodName;   
                   this.params=params;   
                     
                   progressDialog=ProgressDialog.show(MainActivity.this, "提示","正在请求请稍等......", true);   
                   this.start();   
                }   
           /**  
            * 线程运行  
            */  
        @Override  
        public void run() {   
                // TODO Auto-generated method stub   
                System.out.println("jack");   
                super.run();   
                try{   
                        //web service请求   
                        SoapObject result=(SoapObject) CallWebService();   
                        //构造数据   
                        ArrayList<String> list=null;   
                        if(result !=null && result.getPropertyCount() > 0){   
                                list=new ArrayList<String>();   
                                   
                                for(int i=0;i<result.getPropertyCount();i++){   
                                        SoapPrimitive value=(SoapPrimitive) result.getProperty(i);   
                                        list.add(value.toString());   
                                }   
                                   
                                //a取消进度对话框   
                                progressDialog.dismiss();   
                                //构造消息   
                                Message message=handle.obtainMessage();   
                                Bundle b=new Bundle();   
                                b.putStringArrayList("data", list);   
                                message.setData(b);   
                                handle.sendMessage(message);   
                        }   
                }catch(Exception ex){   
                        ex.printStackTrace();   
                }finally{   
                           
                }   
        }   
           
        /**  
         * 请求web service  
         */  
        protected Object CallWebService(){   
                String SOAP_ACTION = nameSpace + methodName;    
                //创建SoapObject实例   
                SoapObject request=new SoapObject(nameSpace,methodName);   
                //生成调用web service方法的soap请求消息   
                SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);   
                //设置.net web service   
                envelope.dotNet=true;   
                //发送请求   
                envelope.setOutputSoapObject(request);   
                //请求参数   
                if(params != null && !params.isEmpty() ){   
                        for(Iterator it=params.entrySet().iterator();it.hasNext();){   
                                Map.Entry e=(Entry) it.next();   
                                request.addProperty(e.getKey().toString(),e.getValue());   
                        }   
                }   
                //   
                HttpTransportSE ht = new HttpTransportSE(url);
                ht.debug=true;

                SoapObject result=null;   
                try{   
                        //web service请求   
                        ht.call(SOAP_ACTION, envelope);   
                        //得到返回结果   
                        result=(SoapObject) envelope.getResponse();   
                }catch(Exception ex){   
                        ex.printStackTrace();   
                }   
                return result;   
                   
        }   
   }   
}