`

【android】访问web service(大概功能版)

 
阅读更多
增加功能:
1,用户点击次数过快。提示。
2,增加progressBar在线程连接web service的时候出现。
3,增加ksoap连接超时。默认链接超时时间过长。体验不好。
4,网络超时连接提示。

layout xml
<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" >

    <!-- 建立一个progressbar当进程在进行处理的时候会出现 -->
    <ProgressBar 
        android:id="@+id/processBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleSmallTitle" />
    
    <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 java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
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.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

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);
//      窗口进度栏可见
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_main);
        setProgressBarIndeterminateVisibility(false);
        
        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
				setProgressBarIndeterminateVisibility(true);
				if (processFlag) {  
					processFlag = false;;//  
					new Thread(new MyThread()).start();
	                new TimeThread().start();  
	             }else{
	            	 setProgressBarIndeterminateVisibility(false);
	            	 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"));
			
			String str = b.getString("value");
			String flag = str.substring(0, str.indexOf("#"));
			String json = str.substring(str.indexOf("#")+1,str.length());
			System.out.println(flag);
			System.out.println();
			
			
			if("1".equals(flag)){
				Gson g2 = new Gson();
				List<Person> p = g2.fromJson(json,  new TypeToken<List<Person>>(){}.getType());
				System.out.println(p.size());
				for(int i=0;i<p.size();i++){
					System.out.println(p.get(i).getName());
				}
				setProgressBarIndeterminateVisibility(false);
				tv2.setText(p.get(0).getName());
			}else{
				setProgressBarIndeterminateVisibility(false);
				tv2.setText(json);
			}
			
			/* */
//			tv2.setText(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 = "";
			String values = "0#网络连接失败";
//			超时时间5秒
			ht = new HttpTransportSE(SERVICE_URL,5000);
	        ht.debug = true;
	        //使用soap1.1协议创建Envelop对象
	        envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
	        //实例化SoapObject对象
	        SoapObject request = new SoapObject(SERVICE_NS, "reJson");
	        
//	        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";
					}
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (XmlPullParserException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				b.putString("value", values);
				msg.setData(b);
				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;
    }
}


在Androidmanifest中记得加入网络读的权限。
<uses-permission android:name="android.permission.INTERNET" />
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics