package com.nenglong.wsclient;
import java.io.IOException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.StrictMode;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
/**
* @author huanglong Android 平臺調用WebService(手機號碼歸屬地查詢)
*/
public class MainActivity extends Activity {
private TextView tv_result;
private EditText et_phone;
private Button btn_query;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
tv_result = (TextView) findViewById(R.id.result_text);
et_phone = (EditText) findViewById(R.id.et);
btn_query = (Button) findViewById(R.id.btn_query);
btn_query.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String phone = et_phone.getText().toString().trim();
if ("".equals(phone) || phone.length() < 7) {
et_phone.setText("您輸入的手機號碼有誤");
et_phone.requestFocus();
tv_result.setText("");
return;
}
getRemoteInfo(phone);
}
});
}
/**
* 查詢號碼段歸屬地的方法
*
* @param phone
* 手機號碼段
*/
public void getRemoteInfo(final String phone) {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
// 命名空間
String nameSpace = "http://WebXml.com.cn/";
// 調用方法的名稱
String methodName = "getMobileCodeInfo";
// EndPoint
String endPoint = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
// SOAP Action
String soapAction = "http://WebXml.com.cn/getMobileCodeInfo";
// 指定WebService的命名空間和調用方法
SoapObject soapObject = new SoapObject(nameSpace, methodName);
// 設置需要調用WebService接口的兩個參數mobileCode UserId
soapObject.addProperty("mobileCode", phone);
soapObject.addProperty("userId", "");
// 生成調用WebService方法調用的soap信息,並且指定Soap版本
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER10);
envelope.bodyOut = soapObject;
// 是否調用DotNet開發的WebService
envelope.dotNet = true;
envelope.setOutputSoapObject(soapObject);
HttpTransportSE transport = new HttpTransportSE(endPoint);
try {
transport.call(soapAction, envelope);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 獲取返回的數據
SoapObject object = (SoapObject) envelope.bodyIn;
// 獲取返回的結果
String result = object.getProperty(0).toString();
Message message = handler.obtainMessage();
message.obj = result;
handler.sendMessage(message);
}
}).start();
}
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
// 將WebService得到的結果返回給TextView
tv_result.setText(msg.obj.toString());
};
};
}
webService:基於SOAP協議的遠程調用標準,通過webService可以將不用的操作系統平臺,不同的計算機語言,不同的技術整合到一起。
調用webService需要導入jar包:ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar包,這個包在網上可以下載,至於導入的方法 ,右鍵項目,選擇最後一項properties-->Java build path-->Libraies-->Add external Jars 選擇相應的路徑下的jar文件就OK了,然後記得在Order and Export 裏面將選擇的jar文件勾選上。
調用webService的步驟分爲7個:
1. 實例化soapObject對象,指定Soap的命名空間(從相關文檔中可以查看WSDL命名空間以及調用方法)
View Code
//命名空間
private static final String serviceNameSpace="http://WebXml.com.cn/";
//調用方法(獲得支持的城市)
private static final String getSupportCity="getSupportCity";
//實例化SoapObject對象
SoapObject request=new SoapObject(serviceNameSpace, getSupportCity);
2.假設方法有參數的話,添加調用的方法的參數
request.addProperties("參數名稱","參數值");
3.設置SOAP請求信息(參數部分爲SOAP版本號,與自己要調用的SOAP版本必須一致,也就是你導入到工程中的jar相對應的版本)
//獲得序列化的Envelope
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=request;
4.註冊Enelope
(new MarshalBase64()).register(envelope);
5.構建傳輸對象,並指定WDSL文檔中的URL
//請求URL
private static final String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
//Android傳輸對象
AndroidHttpTransport transport=new AndroidHttpTransport(serviceURL);
transport.debug=true;
6.調用webService(其中參數爲1:命名空間+方法名稱,envelope對象);
transport.call(serviceNameSpace+getWeatherbyCityName, envelope);
7.解析返回數據:
View Code
if(envelope.getResponse()!=null){
return parse(envelope.bodyIn.toString());
}
/**************
* 解析XML
* @param str
* @return
*/
private static List<String> parse(String str){
String temp;
List<String> list=new ArrayList<String>();
if(str!=null && str.length()>0){
int start=str.indexOf("string");
int end=str.lastIndexOf(";");
temp=str.substring(start, end-3);
String []test=temp.split(";");
for(int i=0;i<test.length;i++){
if(i==0){
temp=test[i].substring(7);
}else{
temp=test[i].substring(8);
}
int index=temp.indexOf(",");
list.add(temp.substring(0, index));
}
}
return list;
}
這樣就成功了,這裏有個地址是提供Webservice天氣預報服務的,我們這裏只提供了獲取城市列表:
View Code
//命名空間
private static final String serviceNameSpace="http://WebXml.com.cn/";
//請求URL
private static final String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
//調用方法(獲得支持的城市)
private static final String getSupportCity="getSupportCity";
//調用城市的方法(需要帶參數)
private static final String getWeatherbyCityName="getWeatherbyCityName";
//調用省或者直轄市的方法(獲得支持的省份或直轄市)
private static final String getSupportProvince="getSupportProvince";
在瀏覽器中輸入WSDL serverUrl 就可以看到一些可供調用的方法:
我們選擇國內外主要城市或者省份的調用方法:getSurpportPrivence(),然後調用之後你會發現返回給我們的是XML文檔
View Code
<?xml version="1.0" encoding="utf-8" ?>
- <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://WebXml.com.cn/">
<string>直轄市</string>
<string>特別行政區</string>
<string>黑龍江</string>
<string>吉林</string>
<string>遼寧</string>
<string>內蒙古</string>
<string>河北</string>
<string>河南</string>
<string>山東</string>
<string>山西</string>
<string>江蘇</string>
<string>安徽</string>
<string>陝西</string>
<string>寧夏</string>
<string>甘肅</string>
<string>青海</string>
<string>湖北</string>
<string>湖南</string>
<string>浙江</string>
<string>江西</string>
<string>福建</string>
<string>貴州</string>
<string>四川</string>
<string>廣東</string>
<string>廣西</string>
<string>雲南</string>
<string>海南</string>
<string>新疆</string>
<string>西藏</string>
<string>臺灣</string>
<string>亞洲</string>
<string>歐洲</string>
<string>非洲</string>
<string>北美洲</string>
<string>南美洲</string>
<string>大洋洲</string>
</ArrayOfString>
View Code
public class WebServiceHelper {
//WSDL文檔中的命名空間
private static final String targetNameSpace="http://WebXml.com.cn/";
//WSDL文檔中的URL
private static final String WSDL="http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
//需要調用的方法名(獲得本天氣預報Web Services支持的洲、國內外省份和城市信息)
private static final String getSupportProvince="getSupportProvince";
//需要調用的方法名(獲得本天氣預報Web Services支持的城市信息,根據省份查詢城市集合:帶參數)
private static final String getSupportCity="getSupportCity";
//根據城市或地區名稱查詢獲得未來三天內天氣情況、現在的天氣實況、天氣和生活指數
private static final String getWeatherbyCityName="getWeatherbyCityName";
/********
* 獲得州,國內外省份和城市信息
* @return
*/
public List<String> getProvince(){
List<String> provinces=new ArrayList<String>();
String str="";
SoapObject soapObject=new SoapObject(targetNameSpace,getSupportProvince);
//request.addProperty("參數", "參數值");調用的方法參數與參數值(根據具體需要可選可不選)
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(soapObject);//envelope.bodyOut=request;
AndroidHttpTransport httpTranstation=new AndroidHttpTransport(WSDL);
//或者HttpTransportSE httpTranstation=new HttpTransportSE(WSDL);
try {
httpTranstation.call(targetNameSpace+getSupportProvince, envelope);
SoapObject result=(SoapObject)envelope.getResponse();
//下面對結果進行解析,結構類似json對象
//str=(String) result.getProperty(6).toString();
int count=result.getPropertyCount();
for(int index=0;index<count;index++){
provinces.add(result.getProperty(index).toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return provinces;
}
/**********
* 根據省份或者直轄市獲取天氣預報所支持的城市集合
* @param province
* @return
*/
public List<String> getCitys(String province){
List<String> citys=new ArrayList<String>();
SoapObject soapObject=new SoapObject(targetNameSpace,getSupportCity);
soapObject.addProperty("byProvinceName", province);
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(soapObject);
AndroidHttpTransport httpTransport=new AndroidHttpTransport(WSDL);
try {
httpTransport.call(targetNameSpace+getSupportCity, envelope);
SoapObject result=(SoapObject)envelope.getResponse();
int count=result.getPropertyCount();
for(int index=0;index<count;index++){
citys.add(result.getProperty(index).toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return citys;
}
/***************************
* 根據城市信息獲取天氣預報信息
* @param city
* @return
***************************/
public WeatherBean getWeatherByCity(String city){
WeatherBean bean=new WeatherBean();
SoapObject soapObject=new SoapObject(targetNameSpace,getWeatherbyCityName);
soapObject.addProperty("theCityName",city);//調用的方法參數與參數值(根據具體需要可選可不選)
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(soapObject);//envelope.bodyOut=request;
AndroidHttpTransport httpTranstation=new AndroidHttpTransport(WSDL);
//或者HttpTransportSE httpTranstation=new HttpTransportSE(WSDL);
try {
httpTranstation.call(targetNameSpace+getWeatherbyCityName, envelope);
SoapObject result=(SoapObject)envelope.getResponse();
//下面對結果進行解析,結構類似json對象
bean=parserWeather(result);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bean;
}
/**
* 解析返回的結果
* @param soapObject
*/
protected WeatherBean parserWeather(SoapObject soapObject){
WeatherBean bean=new WeatherBean();
List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
Map<String,Object> map=new HashMap<String,Object>();
//城市名
bean.setCityName(soapObject.getProperty(1).toString());
//城市簡介
bean.setCityDescription(soapObject.getProperty(soapObject.getPropertyCount()-1).toString());
//天氣實況+建議
bean.setLiveWeather(soapObject.getProperty(10).toString()+"\n"+soapObject.getProperty(11).toString());
//其他數據
//日期,
String date=soapObject.getProperty(6).toString();
//---------------------------------------------------
String weatherToday="今天:" + date.split(" ")[0];
weatherToday+="\n天氣:"+ date.split(" ")[1];
weatherToday+="\n氣溫:"+soapObject.getProperty(5).toString();
weatherToday+="\n風力:"+soapObject.getProperty(7).toString();
weatherToday+="\n";
List<Integer> icons=new ArrayList<Integer>();
icons.add(parseIcon(soapObject.getProperty(8).toString()));
icons.add(parseIcon(soapObject.getProperty(9).toString()));
map.put("weatherDay", weatherToday);
map.put("icons",icons);
list.add(map);
//-------------------------------------------------
map=new HashMap<String,Object>();
date=soapObject.getProperty(13).toString();
String weatherTomorrow="明天:" + date.split(" ")[0];
weatherTomorrow+="\n天氣:"+ date.split(" ")[1];
weatherTomorrow+="\n氣溫:"+soapObject.getProperty(12).toString();
weatherTomorrow+="\n風力:"+soapObject.getProperty(14).toString();
weatherTomorrow+="\n";
icons=new ArrayList<Integer>();
icons.add(parseIcon(soapObject.getProperty(15).toString()));
icons.add(parseIcon(soapObject.getProperty(16).toString()));
map.put("weatherDay", weatherTomorrow);
map.put("icons",icons);
list.add(map);
//--------------------------------------------------------------
map=new HashMap<String,Object>();
date=soapObject.getProperty(18).toString();
String weatherAfterTomorrow="後天:" + date.split(" ")[0];
weatherAfterTomorrow+="\n天氣:"+ date.split(" ")[1];
weatherAfterTomorrow+="\n氣溫:"+soapObject.getProperty(17).toString();
weatherAfterTomorrow+="\n風力:"+soapObject.getProperty(19).toString();
weatherAfterTomorrow+="\n";
icons=new ArrayList<Integer>();
icons.add(parseIcon(soapObject.getProperty(20).toString()));
icons.add(parseIcon(soapObject.getProperty(21).toString()));
map.put("weatherDay", weatherAfterTomorrow);
map.put("icons",icons);
list.add(map);
//--------------------------------------------------------------
bean.setList(list);
return bean;
}
//解析圖標字符串
private int parseIcon(String data){
// 0.gif,返回名稱0,
int resID=32;
String result=data.substring(0, data.length()-4).trim();
// String []icon=data.split(".");
// String result=icon[0].trim();
// Log.e("this is the icon", result.trim());
if(!result.equals("nothing")){
resID=Integer.parseInt(result.trim());
}
return resID;
//return ("a_"+data).split(".")[0];
}
}
以及幫助類:
View Code
public class WebServiceUtil {
//命名空間
private static final String serviceNameSpace="http://WebXml.com.cn/";
//請求URL
private static final String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
//調用方法(獲得支持的城市)
private static final String getSupportCity="getSupportCity";
//調用城市的方法(需要帶參數)
private static final String getWeatherbyCityName="getWeatherbyCityName";
//調用省或者直轄市的方法(獲得支持的省份或直轄市)
private static final String getSupportProvince="getSupportProvince";
/*************
* @return城市列表
*************/
public static List<String> getCityList(){
//實例化SoapObject對象
SoapObject request=new SoapObject(serviceNameSpace, getSupportCity);
//獲得序列化的Envelope
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=request;
(new MarshalBase64()).register(envelope);
//Android傳輸對象
AndroidHttpTransport transport=new AndroidHttpTransport(serviceURL);
transport.debug=true;
//調用
try {
transport.call(serviceNameSpace+getWeatherbyCityName, envelope);
if(envelope.getResponse()!=null){
return parse(envelope.bodyIn.toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static List<String> getProviceList(){
//實例化SoapObject對象
SoapObject request=new SoapObject(serviceNameSpace, getSupportProvince);
//獲得序列化的Envelope
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=request;
(new MarshalBase64()).register(envelope);
//Android傳輸對象
AndroidHttpTransport transport=new AndroidHttpTransport(serviceURL);
transport.debug=true;
//調用
try {
transport.call(serviceNameSpace+getWeatherbyCityName, envelope);
if(envelope.getResponse()!=null){
return null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/*************
* @param cityName
* @return
*************/
public static String getWeather(String cityName){
return "";
}
/**************
* 解析XML
* @param str
* @return
*/
private static List<String> parse(String str){
String temp;
List<String> list=new ArrayList<String>();
if(str!=null && str.length()>0){
int start=str.indexOf("string");
int end=str.lastIndexOf(";");
temp=str.substring(start, end-3);
String []test=temp.split(";");
for(int i=0;i<test.length;i++){
if(i==0){
temp=test[i].substring(7);
}else{
temp=test[i].substring(8);
}
int index=temp.indexOf(",");
list.add(temp.substring(0, index));
}
}
return list;
}
/*********
* 獲取天氣
* @param soapObject
*/
private void parseWeather(SoapObject soapObject){
//String date=soapObject.getProperty(6);
}
}
以上就是顯示天氣預報的全部代碼
轉載自:http://www.cnblogs.com/zhangdongzi/archive/2011/04/19/2020688.html
還可以調用免費的WebService顯示手機號碼的歸屬地,但是每天免費的次數是有限的,同樣是調用WebService
但是調用WebService的時候,因爲是網絡操作,在Android 4.0.3以上的版本貌似會出現異常,後經過google發現是在
新版的Android系統裏面,因爲對網絡的訪問限制的更加嚴格,所以會報NetWorkOnMainThreadException 說的是對
於網絡的訪問不能放在主線程,這樣的解決方案有兩種,一種是開闢新的現成訪問網絡,call webService放在子線程中運行
還有一個解決方案是使用StricMode進行優化,strictMode有很多不同的策略進行優化,當開發者違背某個規則的時候,每個策略都
有不用的方法去提示用戶。
顯示號碼歸屬地的代碼:
package com.nenglong.wsclient;
import java.io.IOException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.StrictMode;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
/**
* @author huanglong Android 平臺調用WebService(手機號碼歸屬地查詢)
*/
public class MainActivity extends Activity {
private TextView tv_result;
private EditText et_phone;
private Button btn_query;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
tv_result = (TextView) findViewById(R.id.result_text);
et_phone = (EditText) findViewById(R.id.et);
btn_query = (Button) findViewById(R.id.btn_query);
btn_query.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String phone = et_phone.getText().toString().trim();
if ("".equals(phone) || phone.length() < 7) {
et_phone.setText("您輸入的手機號碼有誤");
et_phone.requestFocus();
tv_result.setText("");
return;
}
getRemoteInfo(phone);
}
});
}
/**
* 查詢號碼段歸屬地的方法
*
* @param phone
* 手機號碼段
*/
public void getRemoteInfo(final String phone) {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
// 命名空間
String nameSpace = "http://WebXml.com.cn/";
// 調用方法的名稱
String methodName = "getMobileCodeInfo";
// EndPoint
String endPoint = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
// SOAP Action
String soapAction = "http://WebXml.com.cn/getMobileCodeInfo";
// 指定WebService的命名空間和調用方法
SoapObject soapObject = new SoapObject(nameSpace, methodName);
// 設置需要調用WebService接口的兩個參數mobileCode UserId
soapObject.addProperty("mobileCode", phone);
soapObject.addProperty("userId", "");
// 生成調用WebService方法調用的soap信息,並且指定Soap版本
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER10);
envelope.bodyOut = soapObject;
// 是否調用DotNet開發的WebService
envelope.dotNet = true;
envelope.setOutputSoapObject(soapObject);
HttpTransportSE transport = new HttpTransportSE(endPoint);
try {
transport.call(soapAction, envelope);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 獲取返回的數據
SoapObject object = (SoapObject) envelope.bodyIn;
// 獲取返回的結果
String result = object.getProperty(0).toString();
Message message = handler.obtainMessage();
message.obj = result;
handler.sendMessage(message);
}
}).start();
}
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
// 將WebService得到的結果返回給TextView
tv_result.setText(msg.obj.toString());
};
};
}