【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>
Finish Whatever U've Started !!!


浙公網安備 33010602011771號