Android uses SOAP to call the remote WebService and androidwebservice

Source: Internet
Author: User

Android uses SOAP to call the remote WebService and androidwebservice

In today's applications, the network cannot be used, and the backend must be supported by servers. Currently, the most common call methods are http get and POST methods, which return JSON or XML data. However, there is also a common form of calling WebService. Now we can call WebService data using the simple SOAP Object Access Protocol on Android. The main requirement is to return the carrier, card type, and home location information of a mobile phone number.

(1) first download a ksoap jar package from the Internet, put in the libs folder of the project, I also provide Baidu Network Disk download: http://pan.baidu.com/s/1o6svnC2.

(2) recommend a website that can call WebService, the above provides a lot of services, http://www.webxml.com.cn/zh_cn/index.aspx.

(3) The implementation code in the Activity is as follows: it mainly displays the interface and initializes some WebService call parameters, such as URL address, namespace, method name, and parameter list.

Package com. example. testwebservice2; import java. util. hashMap; import android. app. activity; import android. content. context; 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. textView; public class WebserviceActivity extends Activit Y {private Context context; private static final String URL = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx"; // The requested urlprivate static final String NAMESPACE = "http://WebXml.com.cn/"; // The requested NAMESPACE; private static final String METHODNAME = "getMobileCodeInfo"; // method name, which is used to obtain information about the province, region, and phone card type of the mobile phone number in mainland China; private EditText phoneNum; private Button query; private TextView showResult; private Handler handl Er = new Handler () {// refresh the interface; public void handleMessage (Message msg) {String myData = msg. getData (). getString ("data"); // The data is parsed completely; used for display; if (myData! = Null |! "". Equals (myData) {showResult. setText (myData) ;}};@overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); this. context = this; initView (); query. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// mobile phone number (segment) String phoneSec = phoneNum. getText (). toString (). trim (); // you can easily determine whether the entered mobile phone number (segment) is legal if ("". equals (phon ESec) | phoneSec. length () <7) {// The input is invalid. phoneNum. setError ("your mobile phone number (segment) is incorrect! "); // The error code phoneNum is displayed. requestFocus (); // clear the TextView that displays the query results to phoneNum. setText (""); return;} ResponseOnClick (); // The input is correct. Request data starts;}) ;}private void initView () {phoneNum = (EditText) findViewById (R. id. phone_sec); query = (Button) findViewById (R. id. query_btn); showResult = (TextView) findViewById (R. id. result_text);} private void ResponseOnClick () {HttpThread thread = new HttpThread (handler, context); HashMap <String, Object> params = new HashMap <String, Object> (); string phoneSec = phoneNum. getText (). toString (). trim (); // phone number; params. put ("mobileCode", phoneSec); // mobileCode: String, mobile phone number, minimum first seven digits; params. put ("userId", ""); // string. The free user is a Null String. thread. doStart (URL, NAMESPACE, METHODNAME, params );}}

(4) Create a New Thread class that inherits from the Thread and mainly performs network operations to access WebService. Receives the returned data and passes it to the Activity.

Package com. example. testwebservice2; import java. util. hashMap; import java. util. iterator; 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. progressDialog; import and Roid. content. context; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. util. log; class HttpThread extends Thread {private Handler handler = null; private Context context = null; private String url = null; private String namespace = null; private String methodName = null; hashMap <String, Object> params = new HashMap <String, Object> (); // parameter list; private ProgressDialo G progressDialog = null; // constructor public HttpThread (Handler handler, Context context) {this. handler = handler; this. context = context;}/***** startup thread * // *** the four parameters to be passed to the server are: (1) URL (2) namespace (3) method Name (4) parameter list ** @ param url * @ param namespace * @ param methodName * @ param params */public void doStart (String url, String namespace, String methodName, hashMap <String, Object> params) {this. url = url; this. namespace = Namespace; this. methodName = methodName; this. params = params; progressDialog = ProgressDialog. show (context, "prompt", "requesting... please wait... ", true); this. start (); // start this thread;}/*** thread run */@ Overridepublic void run () {try {// web service request SoapObject result = (SoapObject) callWebService (); Log. I ("HttpThread_getPropertyCount", result. getPropertyCount () + ""); Log. I ("HttpThread_getProperty (0)", result. getProperty (0) +" "); // Construct the data String value = null; if (result! = Null & result. getPropertyCount ()> 0) {for (int I = 0; I <result. getPropertyCount (); I ++) {SoapPrimitive primitive = (SoapPrimitive) result. getProperty (I); value = primitive. toString () ;}/ *** the value obtained here is the value of WebService: 18710498511: Shaanxi Xi'an mobile global pass card * // Log. I ("HttpThread_value", value); // cancel the progress box progressDialog. dismiss (); // construct the Message message Message = handler. obtainMessage (); Bundle bundle = new Bundle (); bund Le. putString ("data", value); // it is passed to the interface for display; message. setData (bundle); handler. sendMessage (message); // it is passed to the handmessage () of the Activity for processing;} // if} catch (Exception e) {e. printStackTrace () ;}}// run (); private Object CallWebService () {String SOAP_ACTION = namespace + methodName; // namespace + method name; soapObject request = new SoapObject (namespace, methodName); // create a SoapObject instance // generate a soap request message SoapSerializati that calls the web service Method OnEnvelope envelope = new SoapSerializationEnvelope (SoapEnvelope. VER11); // set. net web serviceenvelope. dotNet = true; // request parameter if (params! = Null &&! Params. isEmpty () {for (Iterator it = params. entrySet (). iterator (); it. hasNext ();) {Map. entry <String, Object> e = (Entry) it. next (); request. addProperty (e. getKey (). toString (), e. getValue () ;}// send the request envelope. setOutputSoapObject (request); HttpTransportSE transport = new HttpTransportSE (url); SoapObject result = null; try {// web service request transport. call (SOAP_ACTION, envelope); result = (SoapObject) envelope. bodyIn;} catch (Exception ex) {ex. printStackTrace ();} Log. I ("result", result. toString (); return result;} // CallWebService () ;}// HttpThread class;

(5) program running result

.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.