【android】web service访问

android对web service的访问。使用ksoap2-android外部jar。
首先下载jar,附件就是。
加入到libs包中,然后加入classpath。

对客户端服务端web service进行编程。
提供最简单的login。
@WebService(name = "Login", targetNamespace = "http://li.duduli.com/")
public interface Login {
	@WebMethod(operationName = "log", action = "urn:Log")
	public String log(@WebParam(name = "arg0") String name,@WebParam(name = "arg1") String password);
}


@WebService(targetNamespace = "http://li.duduli.com/", endpointInterface = "com.duduli.li.Login", portName = "LoginImplPort", serviceName = "LoginImplService")
public class LoginImpl implements Login {
	@Override
	public String log(String name, String password) {
		// TODO Auto-generated method stub
		if("duduli".equals(name) && "wiki".equals(password)){
			System.out.println("success");
			return "success";
		}else{
			System.out.println("failure");
			return "failure";
		}
	}
}



其后为android客户端编程。
提供布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/userName"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="UserName" />

    <EditText
        android:id="@+id/userName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:ems="10" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/userName"
        android:layout_marginTop="28dp"
        android:text="PassWord" />

    <EditText
        android:id="@+id/passWord"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView3"
        android:layout_alignBottom="@+id/textView3"
        android:layout_alignParentRight="true"
        android:ems="10" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:text="Button" />

    <TextView
        android:id="@+id/retrunValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/passWord"
        android:layout_marginTop="32dp"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>


然后是实现。
package com.duduli.li;

import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
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;

public class MainActivity extends Activity {
	private TextView tv,tv2;
	private Button b;
	private EditText name,password;
	private MyHandler myHandler;
	private HttpTransportSE ht;
	
	private boolean processFlag = true;
//	private Handler handler;
	private SoapSerializationEnvelope envelope;
	private static final String SERVICE_NS = "http://li.duduli.com/";
	private static final String SERVICE_URL="http://10.0.2.2:8080/MyContact/services/LoginImplPort";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b = (Button) this.findViewById(R.id.button1);
        tv = (TextView) this.findViewById(R.id.textView1);
        tv2 = (TextView) this.findViewById(R.id.retrunValue);
        name = (EditText) this.findViewById(R.id.userName);
        password = (EditText) this.findViewById(R.id.passWord);
        myHandler = new MyHandler();
        b.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (processFlag) {  
					processFlag = false;;//  
					new Thread(new MyThread()).start();
	                new TimeThread().start();  
	             }else{
	            	 Toast.makeText(getApplicationContext(), "你点击太快了", Toast.LENGTH_SHORT).show();
	             }
			

			}
		});
    }

    class MyHandler extends Handler{

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			Bundle b = msg.getData();
			tv2.setText(b.getString("value")); 
			System.out.println(b.getString("value"));
		}
    	
    }
    
    class MyThread implements Runnable{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			Message msg = new Message();
			Bundle b = new Bundle();
			String values = "";
	        ht = new HttpTransportSE(SERVICE_URL);
	        ht.debug = true;
	        //使用soap1.1协议创建Envelop对象
	        envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
	        //实例化SoapObject对象
	        SoapObject request = new SoapObject(SERVICE_NS, "log");
	        
	        request.addProperty("arg0", name.getText().toString());
	        request.addProperty("arg1", password.getText().toString());
	        
	        envelope.bodyOut = request;
			//你要执行的方法
				try {
					ht.call(null, envelope);
					if(envelope.getResponse()!=null){
						SoapObject result = (SoapObject) envelope.bodyIn;
						values = result.getProperty(0).toString();
		                
					}else{
						values = "nothing";
					}
					b.putString("value", values);
					System.out.println("ok");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (XmlPullParserException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				msg.setData(b);
//				MainActivity.this.send
				myHandler.sendMessage(msg);
		}
    	
    }
    
    
    /** 
     * 计时线程(防止在一定时间段内重复点击按钮) 
     */  
	private class TimeThread extends Thread {
		public void run() {
			try {
				sleep(1000);
				processFlag = true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


在这里需要指出的是,在android 2.3以后对程序行为进行了规范。不允许主线程对网络等耗时操作进行了。
所以需要handler和多线程的配合。
另外,如果用户按钮点击过快的话,会导致服务器响应比较慢,所以需要设置一个flag和一个定时线程,来限制用户行为。

你可能感兴趣的:(web Service)