Android uses ksoap2 to connect to WebService

Source: Internet
Author: User
Here is an example of self-built online: http://express.ruanko.com/ruanko-express_34/technologyexchange5.html

However, this example is not illustrated on the Internet, and some situations are different, so I wrote it again.

1. obtain and use the kSOAP package

In Android
The SDK does not provide a library to call WebService. Therefore, you must use a third-party SDK to call WebService. The WebService library of PC version is very rich, but these are too large for Android. There are some sdks suitable for WebService clients on mobile phones. ksoap2 is commonly used.

Ksoap2 address: http://code.google.com/p/ksoap2-android/

The latest I downloaded is: ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar

Note:

I made a low-level error when using ksoap2-android: the import org. ksoap2 cannot be
Resolved.
At that time, when I analyzed this problem, I thought it was a problem with eclipse. I couldn't find many methods,

Actually the ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar file I downloaded was wrong and led to a detour.

In http://code.google.com/p/ksoap2-android/wiki/HowToUse? TM = 2
Right-click the page and save it as an HTML file with the same name as a plain text file. Instead of what we want.

I am in
Http://code.google.com/p/ksoap2-android/source/browse/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/2.5.4/ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar
Click View raw file to download the corresponding file correctly.

Select our project, right-click build path-> Add External Archives... Add this downloaded package

After adding the file, right-click our project and choose build path> Configure build path libraries from the context menu.
You can see the following figure:

2. Call WebService in the following steps

1. Specify the WebService namespace and call Method

Import org. ksoap2.serialization. soapobject;
Private Static final string
Namespace = "http://WebXml.com.cn /";
Private Static final
String method_name = "getweatherbycityname ";

Soapobject RPC = new soapobject (namespace,
Method_name); the first parameter of the soapobject class represents the WebService namespace. You can find the WebService namespace from the WSDL document.

The second parameter indicates the name of the WebService method to be called.

2. Set the parameter value of the method to be called. If there is no parameter, it can be omitted. The code for setting the parameter value of the method is as follows:

Rpc. addproperty ("thecityname ",
"Beijing"); note that although the 1st parameters of the addproperty method represent the parameter names of the called methods, however, this parameter value is not necessarily the same as the method parameter name in the WebService class of the server. You only need to set the Parameter order to be the same.

3. Generate the SOAP request information that calls the WebService method.

Soapserializationenvelope envelope = new
Soapserializationenvelope (soapenvelope. ver11 );
Envelope. bodyout =
RPC;
Envelope. DOTNET =
True;
Envelope. setoutputsoapobject (RPC); when creating a soapserializationenvelope object, you must use the soapserializationenvelope class constructor to set the SOAP Protocol version number.

This version number must be set according to the WebService version number on the server.

After creating a soapserializationenvelope object, do not forget to set the bodyout attribute of the soapsoapserializationenvelope class,

The value of this attribute is the soapobject created in step 1.

4. Create an httptransportsse object.

Do not use androidhttptransport ht = new androidhttptransport (URL) here );
This is a class to expire

Private Static string url = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx ";
Httptransportse
Ht = new httptransportse (URL); Ht. DEBUG = true; 5. Call the WebService method using the call method.

Private Static string soap_action = "http://WebXml.com.cn/getWeatherbyCityName ";
Ht. Call (soap_action,
Envelope); some people on the Internet say that the first parameter of the call here is null, but after my test, null is not acceptable.

The 2nd parameters are the soapserializationenvelope object created in step 1.

6. Obtain the returned results of the WebService method.

There are two methods:

1. Use the getresponse method to obtain the returned data.

Private soapobject detail;
Detail = (soapobject)
Envelope. getresponse (); 2. Use bodyin and getproperty.

Private soapobject detail;
Soapobject result =
(Soapobject) envelope. bodyin;
Detail = (soapobject)
Result. getproperty ("getweatherbycitynameresult"); 7. An error occurs during the execution, prompting you that you do not have the permission to access the network.

You need to modify the androidmanifest. xml file and grant the corresponding permissions.

Simply put, add the following line of Configuration:

The complete androidmanifest. xml file is as follows:

Note: In Android, The system. Out. Print () output item is written for debugging.

In the menu: window --> show View --> Other --> Find Android and select logcat to view the output,

If you want to see the output of system. Out. Print () in a separate window, click the green "+" on the logcat interface,

In the Filter Name and by log
Enter system. Out in the tag so that you can view the output of system. Out. Print () on a separate interface !!

1.0 "encoding =" UTF-8 "?>
Http://schemas.android.com/apk/res/android"
Package = "ghj1976.myweather"
Android: versioncode = "1"
Android: versionname = "1.0" type = "codeph" text = "/codeph">

@ Drawable/icon"
Android: Label = "@ string/app_name">
. Myweatheractivity"
Android: Label = "@ string/app_name">

Android. Intent. Action. Main"
/>
Android. Intent. Category. launcher"
/>

Android. Permission. Internet ">

The complete code is as follows:

Package ghj1976.myweather;

Import java. Io. unsupportedencodingexception;

Import Android. App. activity;
Import Android. OS. Bundle;
Import
Android. View. view;
Import Android. widget. Button;
Import
Android. widget. Toast;

Import org. ksoap2.soapenvelope;
Import
Org. ksoap2.serialization. soapobject;
Import
Org. ksoap2.serialization. soapserializationenvelope;
// Import
Org. ksoap2.transport. androidhttptransport;
Import
Org. ksoap2.transport. httptransportse;

Public class myweatheractivity extends activity {

Private button okbutton;

/** Called when the activity is first created .*/
@ Override
Public
Void oncreate (bundle savedinstancestate)
{
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );

Okbutton
= (Button)
This. findviewbyid (R. Id. btn_search );
Okbutton. setonclicklistener (New
Button. onclicklistener (){
@ Override
Public void onclick (view V)
{
String city = "Beijing ";
Getweather (city );
}

});
}

Private Static final string namespace = "http://WebXml.com.cn /";

// WebService address
Private Static string url = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx ";

Private Static final string method_name = "getweatherbycityname ";

Private Static string soap_action = "http://WebXml.com.cn/getWeatherbyCityName ";

Private string weathertoday;

Private soapobject detail;

Public void getweather (string cityname ){
Try
{
System. Out. println ("RPC ------");
Soapobject RPC = new
Soapobject (namespace, method_name );
System. Out. println ("RPC" +
RPC );
System. Out. println ("cityname is" +
Cityname );
Rpc. addproperty ("thecityname", cityname );


Soapserializationenvelope envelope = new
Soapserializationenvelope (soapenvelope. ver11 );
Envelope. bodyout =
RPC;
Envelope. DOTNET =
True;
Envelope. setoutputsoapobject (RPC );

Httptransportse ht =
New httptransportse (URL );

// Androidhttptransport ht = new
Androidhttptransport (URL );
Ht. DEBUG = true;

Ht. Call (soap_action, envelope );
// Ht. Call (null, envelope );

// Soapobject result = (soapobject) envelope. bodyin;
// Detail =
(Soapobject) result. getproperty ("getweatherbycitynameresult ");

Detail = (soapobject)
Envelope. getresponse ();

// System. Out. println ("result" +
Result );
System. Out. println ("detail" + detail );
Toast. maketext (this,
Detail. tostring (), Toast. length_long). Show ();
Parseweather (detail );

Return;
} Catch (exception E)
{
E. printstacktrace ();
}
}

Private void parseweather (soapobject detail)
Throws
Unsupportedencodingexception {
String date =
Detail. getproperty (6). tostring ();
Weathertoday = "Today:" + date. Split ("
") [0];
Weathertoday = weathertoday + "\ n weather:" + date. Split ("
") [1];
Weathertoday = weathertoday + "\ n temperature :"
+
Detail. getproperty (5). tostring ();
Weathertoday = weathertoday +
"\ N wind power :"
+ Detail. getproperty (7). tostring () +
"\ N ";
System. Out. println ("weathertoday is" +
Weathertoday );
Toast. maketext (this, weathertoday,
Toast. length_long). Show ();

}
}

References

Access WebService Interface in Android
Http://www.cnblogs.com/yy-7years/archive/2011/01/24/1943286.html

Android calls WebService
Http://express.ruanko.com/ruanko-express_34/technologyexchange5.html

WebService address of China Meteorological Administration
Http://www.webxml.com.cn/WebServices/WeatherWebService.asmx

Android and server-side data interaction (Integrate Android + WebService Based on SOAP protocol)
Http://www.cnblogs.com/zhangdongzi/archive/2011/04/19/2020688.html

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.