Web service example for displaying weather in Android Program

Source: Internet
Author: User
Tags dotnet

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. PC-based WebService libraries are 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/

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 com. duandian;
Import java. Io. unsupportedencodingexception;
Import org. ksoap2.soapenvelope;
Import org. ksoap2.serialization. soapobject;
Import org. ksoap2.serialization. soapserializationenvelope;
Import org. ksoap2.transport. androidhttptransport;
Import org. ksoap2.transport. httptransportse;
Import Android. App. activity;
Import Android. OS. Bundle;
Import Android. View. view;
Import Android. View. View. onclicklistener;
Import Android. widget. Button;
Import Android. widget. edittext;
Import Android. widget. Toast;
Public class weatherforcastactivity extends activity {

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 edittext et;
Private button okbutton;
Private soapobject detail;
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
Okbutton = (button) findviewbyid (R. Id. OK );
ET = (edittext) findviewbyid (R. Id. Et );


// Et. setonclicklistener (New onclicklistener (){
//
// @ Override
// Public void onclick (view v ){
/// Todo auto-generated method stub
//
//}
//});
Okbutton. setonclicklistener (New onclicklistener (){
Public void onclick (view v ){
Charsequence edit_value = ET. gettext ();
String city = edit_value.tostring ();
Getweather (city );
// Showweather ();
}
});
}
// Private void showweather (){
// ET = (edittext) findviewbyid (R. Id. Et );



//}
@ Suppresswarnings ("deprecation ")
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 );
 
Httptransportse ht = new httptransportse (URL );
// Androidhttptransport ht = new androidhttptransport (URL );
Ht. DEBUG = true;
Soapserializationenvelope envelope = new soapserializationenvelope (
Soapenvelope. ver11 );
Envelope. bodyout = RPC;
Envelope. DOTNET = true;
Envelope. setoutputsoapobject (RPC );
Ht. Call (soap_action, envelope );
Soapobject result = (soapobject) envelope. bodyin;
Detail = (soapobject) Result
. Getproperty ("getweatherbycitynameresult ");
System. Out. println ("result" + result );
System. Out. println ("detail" + detail );
Toast. maketext (weatherforcastactivity. 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 (weatherforcastactivity. This, weathertoday,
Toast. length_long). Show ();
}
}
Main. XML code:
<? XML version = "1.0" encoding = "UTF-8"?>
<Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android"
Android: Orientation = "vertical"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
>
<Textview
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: text = "enter the city in which you want to query the weather"
Android: textsize = "30sp"
/>
<Edittext
Android: Id = "@ + ID/ET"
Android: layout_width = "fill_parent"
Android: layout_height = "50dp"
Android: text = ""
/>
<Button
Android: Id = "@ + ID/OK"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: text = "OK"
/>
</Linearlayout>
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.