Home Java javaTutorial Android call WebService instance analysis

Android call WebService instance analysis

Jan 24, 2017 am 10:07 AM

The example of this article describes the method of calling WebService by android. Share it with everyone for your reference. The details are as follows:

WebService is a remote calling standard based on the SOAP protocol. Through webservice, different operating system platforms, different languages, and different technologies can be integrated. There is no library for calling WebService in the Android SDK, so you need to use a third-party SDK to call WebService. The PC version of WEbservice client libraries are very rich, such as Axis2, CXF, etc., but these development kits are too large for the Android system and may not be easily transplanted to the Android system. Therefore, these development kits are not within the scope of our consideration. There are some SDKs for WebService clients suitable for mobile phones. The more commonly used one is Ksoap2, which can be downloaded from http://code.google.com/p/ksoap2-android/downloads/list; the downloaded ksoap2-android-assembly-2.4 -jar-with-dependencies.jar package is copied to the lib directory of the Eclipse project. Of course, it can also be placed in other directories. At the same time, reference this jar package in the Eclipse project.

The java code is as follows:

package com.arg;
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 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 CallWebServiceActivity 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(CallWebServiceActivity.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(CallWebServiceActivity.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()); 
    } 
   }
   //
   AndroidHttpTransport androidHttpTrandsport=new AndroidHttpTransport(url);
   SoapObject result=null;
   try{
    //web service请求
    androidHttpTrandsport.call(SOAP_ACTION, envelope); 
    //得到返回结果
    result=(SoapObject) envelope.getResponse();
   }catch(Exception ex){
    ex.printStackTrace();
   } 
   return result; 
  } 
 } 
}
Copy after login

I hope this article will be helpful to everyone’s Android programming design.

For more articles related to android calling WebService instance analysis, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Mar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How does Java's classloading mechanism work, including different classloaders and their delegation models? How does Java's classloading mechanism work, including different classloaders and their delegation models? Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Mar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

Node.js 20: Key Performance Boosts and New Features Node.js 20: Key Performance Boosts and New Features Mar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Iceberg: The Future of Data Lake Tables Iceberg: The Future of Data Lake Tables Mar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

How can I implement functional programming techniques in Java? How can I implement functional programming techniques in Java? Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

How to Share Data Between Steps in Cucumber How to Share Data Between Steps in Cucumber Mar 07, 2025 pm 05:55 PM

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

See all articles