⑴ 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包下载