package com.ch.day5_httpclient;
import java.util.List;
import com.ch.myutils.NetWorkUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText username;
private EditText userpass;
private Button login;
Context mcontext;
Handler h = new Handler(){
public void handleMessage(android.os.Message msg) {
if(msg.what == 1){
if(msg.obj.equals("success")){
//跳轉
Intent it = new Intent(mcontext,BaseActivity.class);
startActivity(it);
}else{
Toast.makeText(mcontext, "post請求,帳號不對", 0).show();
}
}else if(msg.what == 2){
Toast.makeText(mcontext, (String)msg.obj,0).show();
if(msg.obj.equals("成功")){
//跳轉
Intent it = new Intent(mcontext,BaseActivity.class);
startActivity(it);
}else{
Toast.makeText(mcontext, "post請求,帳號不對", 0).show();
}
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mcontext = MainActivity.this;
init();
}
public void init(){
username = (EditText) findViewById(R.id.username);
userpass = (EditText) findViewById(R.id.userpass);
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//獲得登錄xinix
final String nameValue = username.getText().toString();
final String passValue = userpass.getText().toString();
if(nameValue != null && nameValue != "" && passValue != null && passValue != ""){
//判斷網絡是否開通
if(NetWorkUtil.isNetAvailable(mcontext)){//爲真,表示網絡開通
//獲得服務器請求登錄,經過線程
new Thread(){
public void run() {
//請求服務器
// String rs =
// NetWorkUtil.loginCheck_Get_HttpClient(nameValue, passValue, NetWorkUtil.LOGIN_URL);
// h.sendMessage(h.obtainMessage(1, rs));
String rs =
NetWorkUtil.loginCheck_POST_HttpClient(nameValue, passValue, NetWorkUtil.LOGIN_URL);
h.sendMessage(h.obtainMessage(2, rs));
};
}.start();
}
}else{
Toast.makeText(mcontext, "請完整輸入帳號信息", 0).show();
}
}
});
}
}java
///////////////////////////////////////////////////////////////////////////////////android
package com.ch.myutils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.HttpGet;
package com.ch.myutils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetWorkUtil {
public static final String LOGIN_URL = "http://101.200.142.201:8080/tqyb/login";
public static boolean isNetAvailable(Context context){
//得到網絡管理器
ConnectivityManager connM =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connM.getActiveNetworkInfo();//獲得網絡詳情
if(netInfo == null || !netInfo.isAvailable())
return false;
return true;
}
public static String loginCheck_Get_HttpClient(String name,String pass,String url){
//經過StringBuffer來加工url
StringBuffer sb = new StringBuffer(url);
sb.append("?username=");
sb.append(name);
sb.append("&userpass=");
sb.append(pass);
String result = "";
HttpGet get = new HttpGet(sb.toString());//建立httpClient的get請求對象
//設置請求參數
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 5*1000);
HttpConnectionParams.setSoTimeout(params, 5*1000);
HttpClient client = new DefaultHttpClient(params);//建立HttpClient對象
try {
HttpResponse res = client.execute(get);//執行請求,得到結果
if(res.getStatusLine().getStatusCode() == 200){
HttpEntity entity = res.getEntity();//得到相應結果,是一個HttpEntity對象
result = EntityUtils.toString(entity, "utf-8");//轉換爲字符串
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static String loginCheck_POST_HttpClient(String name,String pass,String url){
String result = "";
HttpPost post = new HttpPost(url);//建立httpClient的post請求對象
//設置請求參數
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 5*1000);
HttpConnectionParams.setSoTimeout(params, 5*1000);
//傳值
//建立List集合,存放向服務器傳遞的數據
List<NameValuePair> reqData = new ArrayList<NameValuePair>();
NameValuePair p1 = new BasicNameValuePair("username", name);
NameValuePair p2 = new BasicNameValuePair("userpass", pass);
reqData.add(p1);
reqData.add(p2);
try {
HttpEntity entity = new UrlEncodedFormEntity(reqData, "utf-8");
post.setEntity(entity);//給post請求對象,設置上傳的數據
HttpClient client = new DefaultHttpClient(params);//建立HttpClient對象
HttpResponse res = client.execute(post);//執行post請求,得到結果
if(res.getStatusLine().getStatusCode() == 200){
HttpEntity resEntity = res.getEntity();//得到相應結果,是一個HttpEntity對象
result = EntityUtils.toString(resEntity, "utf-8");//轉換爲字符串
}
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}apache