好奇Android中是如何使用Webservice的,结果发现Android中没有自带webservice;找了好久才发现有一个jar包叫ksoap2可以进行webservice调用, 好吧 就它了
编写需要的XML文件
<EditText
android:id="@+id/please_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入电话号码"
android:inputType="number" />
<Button
android:id="@+id/start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/start" />
<TextView
android:id="@+id/show_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
编写Activity
public class AndroidToWsActivity extends Activity {
private EditText startSearch;
private TextView show_result;
private Button start;
private String result;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
String obj = (String) msg.obj;
show_result.setText(obj);
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ws);
startSearch = (EditText) findViewById(R.id.please_input);
show_result = (TextView) findViewById(R.id.show_result);
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
result = startSearch.getText().toString().trim();
if ("".equals(result) || result.length() < 7) {
show_result.setText("请输入正确电话号码");
startSearch.setText("");
return;
}
new Thread(new Runnable() {
@Override
public void run() {
Message message = handler.obtainMessage();
message.obj = getRemoteInfo(result);
handler.sendMessage(message);
}
}).start();
}
});
}
public String getRemoteInfo(String phone) {
String nameSpace = "http://WebXml.com.cn/";
String methodName = "getMobileCodeInfo";
String endPoint = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
String soapAction = "http://WebXml.com.cn/getMobileCodeInfo";
SoapObject soapObject = new SoapObject(nameSpace, methodName);
soapObject.addProperty("mobileCode", phone);
soapObject.addProperty("userId", "");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.bodyOut = soapObject;
envelope.dotNet=true;
envelope.setOutputSoapObject(soapObject);
HttpTransportSE httpTransportSE = new HttpTransportSE(endPoint);
try {
httpTransportSE.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("getMobileCodeInfoResult")
.toString();
return result;
}
};
恩,测试就OK了。