⑴ android 連接 web service 失敗 (調用直接進人異常)
trycatch中的內容需要寫一個子線程去執行,即使是一個單獨的類也要寫一個線程的。
你只說會報錯,而錯誤被你攔截了,這樣你根本不知道錯誤原因,我們也無法幫你解決的。
你可以這樣:在catch中e.printStackTrace();後面加上Stringmsg=e.getMessage();
Log.i("msg",msg);來看一下這個錯誤到底是什麼?錯誤列印出來之後看不懂的話可以在網路查一下,一般情況下網路錯誤都會有解決方案的。
⑵ android調用webservice怎麼傳遞對象
1.webservice方法要傳遞參數的對象中包含了日期類型,guid類型。如下所示:
[html] view plain
POST /MyWebService.asmx HTTP/1.1
Host: 192.168.11.62
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/AddMaintenanceInfo"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<AddMaintenanceInfo xmlns="http://tempuri.org/">
<model>
<Id>guid</Id>
<CarId>guid</CarId>
<Cost>string</Cost>
<Dates>dateTime</Dates>
</model>
</AddMaintenanceInfo>
</soap:Body>
</soap:Envelope>
2.新建一個類CarMaintenanceInfo用於傳遞參數對象,並使其實現KvmSerializable,如下
[java] view plain
public class CarMaintenanceInfo implements KvmSerializable {
/**
* 車輛ID
*/
public String CarId;
/**
* 車輛維修費用
*/
public String Cost;
public String Dates;
@Override
public Object getProperty(int arg0) {
switch (arg0) {
case 0:
return CarId;
case 1:
return Cost;
case 2:
return Dates;
default:
break;
}
return null;
}
@Override
public int getPropertyCount() {
return 3;
}
@Override
public void getPropertyInfo(int arg0, Hashtable arg1, PropertyInfo arg2) {
switch (arg0) {
case 0:
arg2.type = PropertyInfo.STRING_CLASS;
arg2.name = "CarId";
break;
case 1:
arg2.type = PropertyInfo.STRING_CLASS;
arg2.name = "Cost";
break;
case 2:
arg2.type = PropertyInfo.STRING_CLASS;
arg2.name = "Dates";
break;
default:
break;
}
}
@Override
public void setProperty(int arg0, Object arg1) {
switch (arg0) {
case 0:
CarId = arg1.toString();
break;
case 1:
Cost = arg1.toString();
break;
case 2:
Dates = arg1.toString();
break;
default:
break;
}
}
}
注意:getPropertyCount的值一定要與該類對象的屬性數相同,否則在傳遞到伺服器時,伺服器收不到部分對象的屬性。
3.編寫請求方法,如下:
[java] view plain
public boolean addMaintenanceInfo(Context context) throws IOException, XmlPullParserException {
String nameSpace = "http://tempuri.org/";
String methodName = "AddMaintenanceInfo";
String soapAction = "http://tempuri.org/AddMaintenanceInfo";
String url = "http://192.168.11.62:6900/MyWebService.asmx?wsdl";// 後面加不加那個?wsdl參數影響都不大
CarMaintenanceInfo info = new CarMaintenanceInfo();
info.setProperty(0, "9fee02c9-8785-4b49-b389-58ed6562c66d");
info.setProperty(1, "12778787");
info.setProperty(2, "2013-07-29T16:45:20");
// 建立webservice連接對象
org.ksoap2.transport.HttpTransportSE transport = new HttpTransportSE(url);
transport.debug = true;// 是否是調試模式
// 設置連接參數
SoapObject soapObject = new SoapObject(nameSpace, methodName);
PropertyInfo objekt = new PropertyInfo();
objekt.setName("model");
objekt.setValue(info);
objekt.setType(info.getClass());
soapObject.addProperty(objekt);
// 設置返回參數
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);// soap協議版本必須用SoapEnvelope.VER11(Soap
// V1.1)
envelope.dotNet = true;// 注意:這個屬性是對dotnetwebservice協議的支持,如果dotnet的webservice
// 不指定rpc方式則用true否則要用false
envelope.bodyOut = transport;
envelope.setOutputSoapObject(soapObject);// 設置請求參數
// new MarshalDate().register(envelope);
envelope.addMapping(nameSpace, "CarMaintenanceInfo", info.getClass());// 傳對象時必須,參數namespace是webservice中指定的,
// claszz是自定義類的類型
try {
transport.call(soapAction, envelope);
// SoapObject sb = (SoapObject)envelope.bodyIn;//伺服器返回的對象存在envelope的bodyIn中
Object obj = envelope.getResponse();// 直接將返回值強制轉換為已知對象
Log.d("WebService", "返回結果:" + obj.toString());
}
catch (IOException e) {
e.printStackTrace();
}
catch (XmlPullParserException e) {
e.printStackTrace();
}
catch (Exception ex) {
ex.printStackTrace();
}
return true;
// 解析返回的結果
// return Boolean.parseBoolean(new AnalyzeUtil().analyze(response));
}
注意:傳遞date類型的時候其實可以使用Date而不是String。但是需要修改幾個地方
1.CarMaintenanceInfo類中的getPropertyInfo(),將arg2.type = PropertyInfo.STRING_CLASS修改為MarshalDate.DATE_CLASS;
2. 在請求方法中的 envelope.setOutputSoapObject(soapObject);下加上 new MarshalDate().register(envelope);
雖然可以使用Date,但是傳到伺服器上的時間與本地時間有時差問題。
當Android 調用webservice,請求參數中有日期,guid,double時,將這些類型在添加對象前轉換為字元串即可。
[java] view plain
// 構造request
SoapObject request = new SoapObject(PublishInfo.NAMESPACE, "GetCarListByRegion");
request.addProperty("leftTopLat", String.valueOf(leftTopLat));
request.addProperty("leftTopLng", String.valueOf(leftTopLng));
request.addProperty("rightBottomLat", String.valueOf(rightBottomLat));
request.addProperty("rightBottomLng", String.valueOf(rightBottomLng));
當需要傳遞一個伺服器對象參數時.
[html] view plain
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetLicenseDetails xmlns="http://tempuri.org/">
<companyId>guid</companyId>
<licenseNos>
<string>string</string>
<string>string</string>
</licenseNos>
<pageOptions>
<page>int</page>
<rows>int</rows>
<total>int</total>
<sort>string</sort>
<order>string</order>
<skip>int</skip>
<Remark>string</Remark>
</pageOptions>
</GetLicenseDetails>
</soap:Body>
</soap:Envelope>
[java] view plain
public ListPageResult<LicenseInfo> getLicenseDetails(String[] licenseNos, int page, int rows, int total) {
// 構造request
SoapObject request = new SoapObject(PublishInfo.NAMESPACE, "GetLicenseDetails");
// 許可證列表
SoapObject deviceObject = new SoapObject(PublishInfo.NAMESPACE, "GetLicenseDetails");
if (licenseNos != null && licenseNos.length > 0) {
for (int i = 0; i < licenseNos.length; i++) {
if (!"".equals(licenseNos[i])) {
deviceObject.addProperty("string", licenseNos[i]);
}
}
request.addProperty("licenseNos", deviceObject);
}
else {
request.addProperty("licenseNos", null);
}
// 分頁數據
SoapObject optionObject = new SoapObject(PublishInfo.NAMESPACE, "PageOptions");
optionObject.addProperty("page", page);
optionObject.addProperty("rows", rows);
optionObject.addProperty("total", total);
optionObject.addProperty("sort", null);
optionObject.addProperty("order", "desc");
optionObject.addProperty("skip", 0);
optionObject.addProperty("Remark", null);
request.addProperty("pageOptions", optionObject);
// 獲取response
Object response = sendRequest(context, request);
if (!mNetErrorHanlder.hasError(response)) { return ObjectAnalyze.getLicenseDetails(response); }
return null;
}
⑶ android 怎麼讀取webservices數據傳參
使用工具soapUI獲取介面調用信息:
雙擊request:
復制介面調用格式:
webService介面通常傳遞xml參數因此需要組裝數據:
①若傳遞單個參數則:
<參數1>參數值
<參數2>參數value
②若傳遞參數最終需要解析成一個對象則:
<屬性>參數值
........
]]>
⑷ android版本更新的webservice怎麼實現
方法/步驟
在eclipse上安裝好android開發環境,android調用webservice使用ksoap,本經驗使用的是ksoap2-android-assembly-2.6.4-jar-with-dependencies.jar
AndroidManifest.xml中需添加相應的許可權,例子:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.camera"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="9" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.camera.MainActivity"
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>
</manifest>
activity_main.xml文件代碼
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="點擊啟動相機"/>
<Button
android:id="@+id/savePic"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="保存圖片到伺服器"/>
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/imageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#999999" />
</LinearLayout>
MainActivity具體代碼
package com.example.camera;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.kobjects.base64.Base64;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tv = null;
String fileName = "/sdcard/myImage/my.jpg"; //圖片保存sd地址
String namespace = "http://webservice.service.com"; // 命名空間
String url = "http://192.168.200.19:8080/Web/webservices/Portal"; //對應的url
String methodName = "uploadImage"; //webservice方法
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.textView);
//啟用相機按鈕
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
}
});
//保存圖片到伺服器按鈕(通過webservice實現)
Button saveButton = (Button) findViewById(R.id.savePic);
saveButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
testUpload();
}
});
}
/**
* 拍照完成後,回掉的方法
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
String sdStatus = Environment.getExternalStorageState();
if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 檢測sd是否可用
Log.v("TestFile",
"SD card is not avaiable/writeable right now.");
return;
}
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data");// 獲取相機返回的數據,並轉換為Bitmap圖片格式
FileOutputStream b = null;
File file = new File("/sdcard/myImage/");
file.mkdirs();// 創建文件夾
try {
b = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把數據寫入文件
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
b.flush();
b.close();
} catch (IOException e) {
e.printStackTrace();
}
}
((ImageView) findViewById(R.id.imageView)).setImageBitmap(bitmap);// 將圖片顯示在ImageView里
}
}
/**
* 圖片上傳方法
*
* 1.把圖片信息通過Base64轉換成字元串
* 2.調用connectWebService方法實現上傳
*/
private void testUpload(){
try{
FileInputStream fis = new FileInputStream(fileName);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count = 0;
while((count = fis.read(buffer)) >= 0){
baos.write(buffer, 0, count);
}
String uploadBuffer = new String(Base64.encode(baos.toByteArray())); //進行Base64編碼
connectWebService(uploadBuffer);
Log.i("connectWebService", "start");
fis.close();
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 通過webservice實現圖片上傳
*
* @param imageBuffer
*/
private void connectWebService(String imageBuffer) {
//以下就是 調用過程了,不明白的話 請看相關webservice文檔
SoapObject soapObject = new SoapObject(namespace, methodName);
soapObject.addProperty("filename", "my.jpg"); //參數1 圖片名
soapObject.addProperty("image", imageBuffer); //參數2 圖片字元串
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = false;
envelope.setOutputSoapObject(soapObject);
HttpTransportSE httpTranstation = new HttpTransportSE(url);
try {
httpTranstation.call(namespace, envelope);
Object result = envelope.getResponse();
Log.i("connectWebService", result.toString());
tv.setText(result.toString());
} catch (Exception e) {
e.printStackTrace();
tv.setText(e.getStackTrace().toString());
}
}
}
服務端webservice方法(cxf)
public String uploadImage(String filename, String image) {
FileOutputStream fos = null;
try{
String toDir = "D:\\work\\image"; //存儲路徑
byte[] buffer = new BASE64Decoder().decodeBuffer(image); //對android傳過來的圖片字元串進行解碼
File destDir = new File(toDir);
if(!destDir.exists()) {
destDir.mkdir();
}
fos = new FileOutputStream(new File(destDir,filename)); //保存圖片
fos.write(buffer);
fos.flush();
fos.close();
return "上傳圖片成功!" + "圖片路徑為:" + toDir;
}catch (Exception e){
e.printStackTrace();
}
return "上傳圖片失敗!";
}
⑸ android調用webservice怎麼授權
具體調用調用webservice的方法為:
(1) 指定webservice的命名空間和調用的方法名,如:
SoapObject request =new SoapObject(http://service,」getName」);
SoapObject類的第一個參數表示WebService的命名空間,可以從WSDL文檔中找到WebService的命名空間。第二個參數表示要調用的WebService方法名。
(2) 設置調用方法的參數值,如果沒有參數,可以省略,設置方法的參數值的代碼如下:
Request.addProperty(「param1」,」value」);
Request.addProperty(「param2」,」value」);
要注意的是,addProperty方法的第1個參數雖然表示調用方法的參數名,但該參數值並不一定與服務端的WebService類中的方法參數名一致,只要設置參數的順序一致即可。
(3) 生成調用Webservice方法的SOAP請求信息。該信息由SoapSerializationEnvelope對象描述,代碼為:
SoapSerializationEnvelope envelope=new
SoapSerializationEnvelope(SoapEnvelope.VER11);
Envelope.bodyOut = request;
創建SoapSerializationEnvelope對象時需要通過SoapSerializationEnvelope類的構造方法設置SOAP協議的版本號。該版本號需要根據服務端WebService的版本號設置。在創建SoapSerializationEnvelope對象後,不要忘了設置SOAPSoapSerializationEnvelope類的bodyOut屬性,該屬性的值就是在第一步創建的SoapObject對象。
(4) 創建HttpTransportsSE對象。通過HttpTransportsSE類的構造方法可以指定WebService的WSDL文檔的URL:
HttpTransportSE ht=new HttpTransportSE(「http://192.168.18.17:80
/axis2/service/SearchNewsService?wsdl」);
(5)使用call方法調用WebService方法,代碼:
ht.call(null,envelope);
Call方法的第一個參數一般為null,第2個參數就是在第3步創建的SoapSerializationEnvelope對象。
(6)使用getResponse方法獲得WebService方法的返回結果,代碼:
SoapObject soapObject =( SoapObject) envelope.getResponse();
⑹ 求助android調用webservice的問題
public String getRemoteInfo(String phoneSec) {
// 設置是否調用的是dotNet開發的WebService
// 命名空間
09-21 16:16:00.610: W/System.err(4839): at android.app.ActivityThread.access$1500(ActivityThread.java:122)
再補充點,錯誤是在三星的平板上運行的,不帶撥號功能
// 設置需調用WebService介面需要傳入的兩個參數mobileCode、userId
String nameSpace = "url/";
// 調用的方法名稱
String methodName = "getMobileCodeInfo";
// EndPoint
String endPoint = "url/WebServices/MobileCodeWS.asmx";
// SOAP Action
String soapAction = "url/getMobileCodeInfo";
// 指定WebService的命名空間和調用的方法名
SoapObject rpc = new SoapObject(nameSpace, methodName);
09-21 16:16:00.600: W/System.err(4839): at java.net.InetAddress.getAllByName(InetAddress.java:249)
rpc.addProperty("mobileCode", phoneSec);
rpc.addProperty("userId", "");
// 生成調用WebService方法的SOAP請求信息,並指定SOAP的版本
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);
envelope.bodyOut = rpc;
envelope.dotNet = true;
// 等價於envelope.bodyOut = rpc;
envelope.setOutputSoapObject(rpc);
// 調用WebService
transport.call(soapAction, envelope);
} catch (Exception e) {
e.printStackTrace();
}
// 獲取返回的數據
SoapObject object = (SoapObject) envelope.bodyIn;
// 獲取返回的結果
return object.getProperty(0).toString();
try {
// 將WebService返回的結果顯示在TextView中
}
⑺ android 訪問webservice 提示找不到webservice文件
Stringmethod=Constant.BILL_COUNT;
StringsoapAction=Constant.NAMESPACE+method;
SoapObjectobject=newSoapObject(Constant.NAMESPACE,method);
HttpTransportSEhts=newHttpTransportSE(
((ClientApp)getApplication()).getServiceAddress());
object.addProperty("billNumber",edit_abnormalnumber.getText()
.toString().trim());
SoapSerializationEnvelopesse=newSoapSerializationEnvelope(
SoapEnvelope.VER12);
sse.dotNet=true;
sse.bodyOut=hts;
sse.setOutputSoapObject(object);
⑻ android怎麼調用webservice
WebService是一種基於SOAP協議的遠程調用標准,通過webservice可以將不同操作系統平台、不同語言、不同技術整合到一塊。在Android SDK中並沒有提供調用WebService的庫,因此,需要使用第三方的SDK來調用WebService。PC版本的WEbservice客戶端庫非常豐富,例如Axis2,CXF等,但這些開發包對於Android系統過於龐大,也未必很容易移植到Android系統中。因此,這些開發包並不是在我們的考慮范圍內。適合手機的WebService客戶端的SDK有一些,比較常用的有Ksoap2,可以從http://code.google.com/p/ksoap2-android/downloads/list進行下載;將下載的ksoap2-android-assembly-2.4-jar-with-dependencies.jar包復制到Eclipse工程的lib目錄中,當然也可以放在其他的目錄里。同時在Eclipse工程中引用這個jar包。
具體調用調用webservice的方法為:
(1) 指定webservice的命名空間和調用的方法名,如:
SoapObject request =new SoapObject(http://service,」getName」);
SoapObject類的第一個參數表示WebService的命名空間,可以從WSDL文檔中找到WebService的命名空間。第二個參數表示要調用的WebService方法名。
(2) 設置調用方法的參數值,如果沒有參數,可以省略,設置方法的參數值的代碼如下:
Request.addProperty(「param1」,」value」);
Request.addProperty(「param2」,」value」);
要注意的是,addProperty方法的第1個參數雖然表示調用方法的參數名,但該參數值並不一定與服務端的WebService類中的方法參數名一致,只要設置參數的順序一致即可。
(3) 生成調用Webservice方法的SOAP請求信息。該信息由SoapSerializationEnvelope對象描述,代碼為:
SoapSerializationEnvelope envelope=new
SoapSerializationEnvelope(SoapEnvelope.VER11);
Envelope.bodyOut = request;
創建SoapSerializationEnvelope對象時需要通過SoapSerializationEnvelope類的構造方法設置SOAP協議的版本號。該版本號需要根據服務端WebService的版本號設置。在創建SoapSerializationEnvelope對象後,不要忘了設置SOAPSoapSerializationEnvelope類的bodyOut屬性,該屬性的值就是在第一步創建的SoapObject對象。
(4) 創建HttpTransportsSE對象。通過HttpTransportsSE類的構造方法可以指定WebService的WSDL文檔的URL:
HttpTransportSE ht=new HttpTransportSE(「http://192.168.18.17:80
/axis2/service/SearchNewsService?wsdl」);
(5)使用call方法調用WebService方法,代碼:
ht.call(null,envelope);
Call方法的第一個參數一般為null,第2個參數就是在第3步創建的SoapSerializationEnvelope對象。
(6)使用getResponse方法獲得WebService方法的返回結果,代碼:
SoapObject soapObject =( SoapObject) envelope.getResponse();
以下為簡單的實現一個天氣查看功能的例子:
publicclass WebService extends Activity {
privatestaticfinal String NAMESPACE ="http://WebXml.com.cn/";
// WebService地址
privatestatic String URL ="http://www.webxml.com.cn/
webservices/weatherwebservice.asmx";
privatestaticfinal String METHOD_NAME ="getWeatherbyCityName";
privatestatic String SOAP_ACTION ="http://WebXml.com.cn/
getWeatherbyCityName";
private String weatherToday;
private Button okButton;
private SoapObject detail;
@Override
publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
okButton = (Button) findViewById(R.id.ok);
okButton.setOnClickListener(new Button.OnClickListener() {
publicvoid onClick(View v) {
showWeather();
}
});
}
privatevoid showWeather() {
String city ="武漢";
getWeather(city);
}
@SuppressWarnings("deprecation")
publicvoid 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);
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(WebService.this, detail.toString(),
Toast.LENGTH_LONG).show();
parseWeather(detail);
return;
} catch (Exception e) {
e.printStackTrace();
}
}
privatevoid parseWeather(SoapObject detail)
throws UnsupportedEncodingException {
String date = detail.getProperty(6).toString();
weatherToday ="今天:"+ date.split("")[0];
weatherToday = weatherToday +"\n天氣:"+ date.split("")[1];
weatherToday = weatherToday +"\n氣溫:"
+ detail.getProperty(5).toString();
weatherToday = weatherToday +"\n風力:"
+ detail.getProperty(7).toString() +"\n";
System.out.println("weatherToday is "+ weatherToday);
Toast.makeText(WebService.this, weatherToday,
Toast.LENGTH_LONG).show();
}
}
⑼ Android 使用KSOAP2調用WebService
android 利用ksoap2方式連接webservice(2010-04-16 16:36:25)轉載標簽:androidksoap2webserviceit 分類:Android
利用J2SE的ksoap2標准,我也來做一個山寨版本的android連接webservice。因為soap封裝的關系,android application在接收到數據後不能夠正確的按照J2SE的標准來獲取。
在運用之前,我們先要引導兩個jar進入工程的buildpath
這兩個jar包都可以在網上查到下載,引導完後再做一項准備工作。弄清楚已發布的webservice的地址,以及封裝的方式。比如:
webservice介面: http://192.168.0.2:8080/axis2/services/Manager?wsdl (順便說明一下,在android當中,不能寫localhost,必須寫清楚PC機當前的網路IP)
webservice封裝: http://ws.apache.org/axis2
都了解了過後,說明已經做好准備了。
下面就介紹一下android如何獲取webservice封裝數據。。
引入ksoap2中以封裝好的類
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
在類中定義webservice的介面地址以及解析方式並且定義要調用的webservice中的函數
private static final String URL = " http://192.168.0.2:8080/axis2/services/Manager?wsdl";
private static final String NAMESPACE = " http://ws.apache.org/axis2";
private static final String METHOD_NAME = "GetMyFriends";
這個信息我們可以在webservice中查到
<xs:element name="GetMyFriends">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" name="userId" type="xs:int"/>
<xs:element minOccurs="0" name="password" nillable="true" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
接下來開始做對webservice請求數據的工作,請求webservice函數以及封裝要用的兩個參數(userId和password)
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("userId", "123456");
request.addProperty("password", "test");
之後我們給定義發送數據的信封的封裝格式
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11 );
發出請求
envelope.setOutputSoapObject(request);
AndroidHttpTransport aht = new AndroidHttpTransport(URL);
aht.call(null, envelope);
接著就可以定義一個SoapObject類型的實例去獲取我們返回來的數據
SoapObject so = (SoapObject) envelope.bodyIn;
這里如果是返回來的數據只有一行並且只有一個值,比如驗證函數,返回boolean類型的話,操作比較簡單,String getReturn= so.getProperty("return"); 這個getReturn就是你要獲取的值。
但是如果返回來是多行的值的話,這個方法就不行了,我們必須對返回來的信息做一些解析。我曾試過用J2SE的標准方式來獲取,但是會報錯,最主要的可能是他的方式在android當中不能使用。所以在這里我用了正則表達式這種方式來進行數據的解析,我們先來看一下他返回的數據的結構是什麼情況。
GetMyFriendsResponse{return=FriendsMessage{ <br>permitList=anyType{nickName=我愛羅; singnature=null; userId=2; }; permitList=anyType{nickName=jack; singnature=null; userId=1004; }; permitList=anyType{nickName=admin; singnature=leo_admin; userId=1001; };};}
簡單看他很想Json結構,但是確不是。。。
就目前的解決方式,我只是通過規律來進行了正則表達式的解析:如解析上面的內容。
//首先取得permitList(好友)的個數
String testPattern = "permitList";
int resultlength = result.length();
cresult = cresult.replace(testPattern, "");
int lastlength = (resultlength - cresult.length()) / testPattern.length();
//取得每個permitList中的值。
String LoginReturn="", pattern="nickName=.*?;\\s*singnature=.*?;\\s*userId=.*?;";
//動態生成String 數組,存儲每個好友的信息
String[] GetFinalReturn = new String[lastlength];
for (int i=0;i<lastlength;i++){
LoginReturn = result.replaceFirst("^.*("+pattern+").*$", "$1");
GetFinalReturn[i] = LoginReturn;
result = result.replace(LoginReturn,"");
}
這個數組裡面存儲的格式就是nickName=admin; singnature=leo_admin; userId=1001;
這樣以來,我們可以根據"="和";"兩個符號之間做split操作就可以得到數據。
好了,到此連接webservice和解析返回來的數據的工作就做完了,雖然這個方式看起來很復雜,但是目前來說,用ksoap2方式來連接webservice暫時還沒有找到更有效的解決方式。。
⑽ android端怎麼調用webservice介面
在Android平台調用Web Service需要依賴於第三方類庫ksoap2,它是一個SOAP Web service客戶端開發包,主要用於資源受限制的Java環境如Applets或J2ME應用程序(CLDC/ CDC/MIDP)。認真讀完對ksoap2的介紹你會發現並沒有提及它應用於Android平台開發,沒錯,在Android平台中我們並不會直接使用ksoap2,而是使用ksoap2 android。KSoap2 Android 是Android平台上一個高效、輕量級的SOAP開發包,等同於Android平台上的KSoap2的移植版本。
Ksoap2-android jar包下載