您可以很容易地在 google 上找到如何创建简单的网络服务。
我想向你展示如何从 .net 网络服务获取数据:
首先,您必须使用 ksoap2 库在 android 中获取数据。
http://code.google.com/p/ksoap2-android/下载并复制到项目>libs文件夹
其次,你必须使用asynctask来调用web服务,因为你必须使用asynctask在android中进行长时间的处理。
如果你下载 ksoap2 库并将其复制到项目中,让我们开始吧。
//import ksoap2
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
public class Example extends Activity {
//define your web service namespace
private static final String NAMESPACE = "http://tempuri.org/";
//web service URL
private static final String URL = "http://www.example.com/webservice1.asmx";
//variables
private String username;
private String password;
private String userID;
public class ExampleAS extends AsyncTask<String,String,String>{
private ProgressDialog dialog = new ProgressDialog(Example.this);
String ParamUserName;
String ParamPassword;
public ExampleAS(String ParamUserName,String ParamPassword){
this.ParamUserName=ParamUserName;
this.ParamPassword=ParamPassword;
}
@Override
protected void onPreExecute() {
dialog.setMessage("Loading...");
dialog.show();
}
@Override
protected String doInBackground(String... params) {
ExampleFunc(ParamUserName,ParamPassword);
return userID;
}
protected void onPostExecute(String userID){
label.setText(userID);
dialog.dismiss();
}
}
private String ExampleFunc(String ParamUserName,String ParamPassword){
PropertyInfo uName = new PropertyInfo();
uName.name= "USERNAME"; //It must be same with your webservice's parameter name
uName.setValue(ParamUserName); //Parameter value
uName.type = PropertyInfo.STRING_CLASS; //Parameter type
PropertyInfo pass = new PropertyInfo();
pass.name= "PASSWORD"; //It must be same with your webservice's parameter name
pass.setValue(ParamPassword); //Parameter value
pass.type = PropertyInfo.STRING_CLASS; //Parameter type
SoapObject request = new SoapObject(NAMESPACE, "Login"); //Namespace,Webservice method name
request.addProperty(uName);
request.addProperty(pass);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=request;
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;
try {
androidHttpTransport.call("http://tempuri.org/Login", envelope);
SoapObject response = (SoapObject) envelope.getResponse();
Object property = response.getProperty(0);
if(property instanceof SoapObject){
SoapObject users = (SoapObject) property;
userID = users.getProperty("user_id").toString();
}
}
catch (Exception e) {
e.printStackTrace();
}
return userID;
}
不要复制和构建它,它可能不起作用,因为我写在这里。您应该为您的请求更改某些字段或从 Web 服务获取数据。
你必须在 onCreate 中调用 asynctask
例如;
new ExampleAS("admin","1234").execute();
最后,你应该关注我的另一个帖子:Get List from .net Web Service on Android