【Android学习笔记】HTTP POST & WorkThread

HTTP Post的简单用法,和多线程的简单用法:

WebService:

  
[WebMethod]
public bool Login( string account, string password)
{
if ( " larrylee " == account & " 123456 " == password)
return true ;
else
return false ;
}

Login Activity:

  
package com.mtk.lc.LoginDemo;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginDemo extends Activity {
EditText editTextAccount;
EditText editTextPsw;
Button buttonLogin;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.main);
editTextAccount
= (EditText) findViewById(R.id.editTextAccount);
editTextPsw
= (EditText) findViewById(R.id.editTextPsw);
buttonLogin
= (Button) findViewById(R.id.buttonLogin);
buttonLogin.setOnClickListener(
new View.OnClickListener() {

@Override
public void onClick(View v) {
List
< NameValuePair > params = new ArrayList < NameValuePair > ();
params.add(
new BasicNameValuePair( " account " , editTextAccount.getText().toString())); // 传递参数
params.add( new BasicNameValuePair( " password " , editTextPsw.getText().toString())); // 传递参数
HTTPThread httpThread = new HTTPThread(loginHandler);
// 在工作线程中执行耗时任务,防止UI线程阻塞
httpThread.doStart( " http://10.0.2.2:2161/WebSite1/Service.asmx/Login " , params, LoginDemo. this );
// 10.0.2.2为电脑对于模拟器而言的IP地址。
}
});
}
private Handler loginHandler = new Handler(){
public void handleMessage(Message message) {
switch (message.what) {
case 1 : // 程序执行正常
Boolean res = message.getData().getBoolean( " login " );
if (res){ // 成功登陆
Toast.makeText(LoginDemo. this , " Successd! " , Toast.LENGTH_LONG).show();
}
else { // 登陆失败
Toast.makeText(LoginDemo. this , " Fail! " , Toast.LENGTH_LONG).show();
}
break ;

default : // 程序异常...(网络连接出错)
Toast.makeText(LoginDemo. this , " Error! " , Toast.LENGTH_LONG).show();
break ;
}
}
};

}

Http Thread

  
package com.mtk.lc.LoginDemo;

import java.io.IOException;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class HTTPThread extends Thread {
ProgressDialog pdDialog
= null ;
String urlString
= null ;
List
< NameValuePair > params = null ;
Handler handler
= null ;

public HTTPThread(Handler handler) {
this .handler = handler;
}

public void doStart(String urlString, List < NameValuePair > params,
Context context) {
// 进行一些初始化工作然后调用start()让线程运行
this .urlString = urlString;
this .params = params;
pdDialog
= new ProgressDialog(context);
pdDialog.setTitle(
" Login... " );
pdDialog.setMessage(
" Connecting to Server... " );
pdDialog.setIndeterminate(
true );
pdDialog.setButton(
" Cancel " , new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
pdDialog.cancel();
}
});
pdDialog.show();
this .start();
}

@Override
public void run() {
Message msg
= new Message();
Bundle data
= new Bundle();
try {
boolean result = webServiceLogin(); // 执行网络服务请求,耗时操作。。。
msg.what = 1 ;
data.putBoolean(
" login " , result);
data.putString(
" info " , " normal " );
msg.setData(data);
}
catch (ParseException e) {
msg.what
= 2 ;
data.putString(
" info " , " Error " );
msg.setData(data);
e.printStackTrace();
}
catch (ClientProtocolException e) {
msg.what
= 2 ;
data.putString(
" info " , " Error " );
msg.setData(data);
e.printStackTrace();
}
catch (IOException e) {
msg.what
= 2 ;
data.putString(
" info " , " Error " );
msg.setData(data);
e.printStackTrace();
}
finally {
pdDialog.dismiss();
handler.sendMessage(msg);
}
}

private boolean webServiceLogin() throws ParseException,
ClientProtocolException, IOException {
HttpClient httpClient
= new DefaultHttpClient(); // HTTP客户端,使用默认客户端
HttpPost httpPost = new HttpPost(urlString); // 建立HttpPost对象
httpPost.setEntity( new UrlEncodedFormEntity(params, HTTP.UTF_8)); // 设置参数
String res = EntityUtils.toString(httpClient.execute(httpPost)
.getEntity());
// 执行并返回结果:

// <?xml version="1.0" encoding="utf-8" ?>
// <boolean xmlns=" http://tempuri.org/ ">true</boolean>

if (res.contains( " true " )) { // 偷个懒不对XML进行解析了,返回中有true就是登陆成功了。
return true ;
}
return false ;
}
}

Layout:

  
<? xml version="1.0" encoding="utf-8" ?>
< LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android"
android:orientation
="vertical" android:layout_width ="fill_parent"
android:layout_height
="fill_parent" >
< TextView android:id ="@+id/textView1" android:layout_width ="wrap_content"
android:layout_height
="wrap_content" android:text ="Account:"
android:textSize
="10pt" ></ TextView >
< EditText android:layout_height ="wrap_content"
android:layout_width
="match_parent" android:id ="@+id/editTextAccount" ></ EditText >
< TextView android:id ="@+id/textView2" android:layout_width ="wrap_content"
android:layout_height
="wrap_content" android:textSize ="10pt"
android:text
="Pass Word:" ></ TextView >
< EditText android:layout_height ="wrap_content"
android:layout_width
="match_parent" android:id ="@+id/editTextPsw"
android:password
="true" ></ EditText >
< Button android:layout_width ="wrap_content"
android:layout_height
="wrap_content" android:id ="@+id/buttonLogin"
android:text
="Login" ></ Button >
</ LinearLayout >

你可能感兴趣的:(Android学习)