Android calls WebService (weather forecast)

Source: Internet
Author: User
Document directory
  • Feedback

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

The android 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? On the TM = 2 page, right-click the link and save it as a plain text HTML file with the same name. 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 it, right-click our project and choose build path> Configure build path libraries from the shortcut menu. The following figure is displayed:

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 name of the method to be called, the parameter value is not necessarily the same as the method parameter name in the WebService class of the server, you only need to set parameters in the same order.

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. Use the call method to call the WebService Method

private static String SOAP_ACTION = "http://WebXml.com.cn/getWeatherbyCityName";ht.call(SOAP_ACTION, envelope);

Someone on the Internet said 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 at this time, 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 add the following configuration line: <uses-Permission Android: Name = "android. Permission. Internet"> </uses-Permission>

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,

Fill in system. Out in the filter name and by log tag, so that you can view the output of system. Out. Print () on a separate interface !!

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="ghj1976.MyWeather" android:versionCode="1"android:versionName="1.0"><application android:icon="@drawable/icon" android:label="@string/app_name"><activity android:name=".MyWeatherActivity" android:label="@string/app_name"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application><uses-permission android:name="android.permission.INTERNET"></uses-permission></manifest>

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. * // @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); okbutton = (button) This. findviewbyid (R. id. btn_search); okbutton. setonclicklistener (New button. onclicklistener () {@ overridepublic 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

The following are the response problems:

Feedback #1 floor reply reference View

By
I followed your steps. Why not ??? It seems that my rack package is incorrect. I don't know why # Check the reference in the reply on the second floor.

By
Feng Jing, I followed the code you wrote and ran it at 07:00:55-24. 589: Error/dalvikvm (315): cocould not find method Org. ksoap2.serialization. soapobject. getproperty, referenced from method BZU. webclinet. webclinetactivity. parseweather
07-24 07:00:55. 599: Error/androidruntime (315): uncaught handler: thread main exiting due to uncaught exception
07-24 07:00:55. 619: Error/androidruntime (315): Java. Lang. verifyerror: BZU. webclinet. webclinetactivity
07-24 07:00:55. 619: Error/androidruntime (315): At java. Lang. Class. newinstanceimpl (native method)
07-24 07:00:55. 619: Error/androidruntime (315): At java. Lang. Class. newinstance (class. Java: 1472)
07-24 07:00:55. 619: Error/androidruntime (315): at Android. App. instrumentation. newactivity (instrumentation. Java: 1097)
07-24 07:00:55. 619: Error/androidruntime (315): at Android. App. activitythread. initialize mlaunchactivity (activitythread. Java: 2316)
07-24 07:00:55. 619: Error/androidruntime (315): at Android. App. activitythread. handlelaunchactivity (activitythread. Java: 2417)
07-24 07:00:55. 619: Error/androidruntime (315): at Android. App. activitythread. Access $2100 (activitythread. Java: 116)
07-24 07:00:55. 619: Error/androidruntime (315): at Android. App. activitythread $ H. handlemessage (activitythread. Java: 1794)
07-24 07:00:55. 619: Error/androidruntime (315): at Android. OS. handler. dispatchmessage (handler. Java: 99)
07-24 07:00:55. 619: Error/androidruntime (315): at Android. OS. Looper. Loop (Looper. Java: 123)
07-24 07:00:55. 619: Error/androidruntime (315): at Android. App. activitythread. Main (activitythread. Java: 4203)
07-24 07:00:55. 619: Error/androidruntime (315): At java. Lang. Reflect. method. invokenative (native method)
07-24 07:00:55. 619: Error/androidruntime (315): At java. Lang. Reflect. method. Invoke (method. Java: 521)
07-24 07:00:55. 619: Error/androidruntime (315): At com. Android. Internal. OS. zygoteinit $ methodandargscaller. Run (zygoteinit. Java: 791)
07-24 07:00:55. 619: Error/androidruntime (315): At com. Android. Internal. OS. zygoteinit. Main (zygoteinit. Java: 549)
07-24 07:00:55. 619: Error/androidruntime (315): At Dalvik. system. nativestart. Main (native method)
How can this problem be solved ?? # View the reply reference on the third floor

By
According to your tutorial, Leito blogger I made a code debugging and showed that it was okay. When I clicked the button on the simulator, it didn't respond! Which controls are contained in the main. xml file ~~ # View the reply reference on the 4th floor

By
Leito knows the reason because no access permission is added in Step 7 ~ I sorted out the source code of this example.

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.