Android 调用.NET webservice
package com.fairyeye.simple; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; public class MiniSystemActivity extends Activity { /** Called when the activity is first created. */ private EditText userName; private EditText userPass; private Button btnLogin; private Button btnClose; private TextView tv; final String SOAP_ACTION = "http://tempuri.org/HelloWorld"; private static final String METHOD_NAME = "HelloWorld"; private static final String NAMESPACE = "http://tempuri.org/"; private static final String URL = "http://10.0.2.2/webser/webtest.asmx"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnLogin = (Button) findViewById(R.id.btnLogin); btnClose = (Button) findViewById(R.id.btnClose); userName = (EditText) findViewById(R.id.userName); userPass = (EditText) findViewById(R.id.userPass); tv = (TextView)findViewById(R.id.txtView); btnLogin.setOnClickListener(listener); call(); } private OnClickListener listener = new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub if (userName.getText().toString().trim().equals("222") && userPass.getText().toString().trim().equals("222")) { Intent intent = new Intent(); intent.setClass(MiniSystemActivity.this, testActivity.class); startActivity(intent); } else { Toast.makeText(MiniSystemActivity.this, "用户或密码错误!", Toast.LENGTH_LONG).show(); } } }; public void call() { try { SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); //request.addProperty("passonString", "Rajapandian"); //这个是传递参数的 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); androidHttpTransport.call(SOAP_ACTION, envelope); Object result = (Object) envelope.getResponse(); tv.setText(result.toString()); } catch (Exception e) { System.out.println(e.getMessage()); tv.setText(e.getMessage()); } } }
---------------------------------以上 实现了 Android内通过Ksoap包的方法 调用了 .net webserivce中 helloworld 方法。
1.在ADT 虚拟机中 localhost/127.0.01是不行的。虚拟机中默认10.0.2.2为本地地址 所以我们在本地的.NET webservice 如果为localhost/webser/webtest.asmx 在Android模拟器中为10.0.2.2/webser/webtest/asmx.(该问题 亲自测试)
2.记得 在AndroidManifest.xml 加入 允许访问 Internet <uses-permission android:name="android.permission.INTERNET" />