HttpClient——Get,Post
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();
}
}
});
}
}
1 package com.ch.myutils;
2
3 import java.io.IOException;
4 import java.io.UnsupportedEncodingException;
5 import java.util.ArrayList;
6 import java.util.List;
7
8 import org.apache.http.HttpEntity;
9 import org.apache.http.HttpResponse;
10 import org.apache.http.NameValuePair;
11 import org.apache.http.client.ClientProtocolException;
12 import org.apache.http.client.HttpClient;
13 import org.apache.http.client.entity.UrlEncodedFormEntity;
14 import org.apache.http.client.methods.HttpGet;
15 package com.ch.myutils;
16
17 import java.io.IOException;
18 import java.io.UnsupportedEncodingException;
19 import java.util.ArrayList;
20 import java.util.List;
21
22 import org.apache.http.HttpEntity;
23 import org.apache.http.HttpResponse;
24 import org.apache.http.NameValuePair;
25 import org.apache.http.client.ClientProtocolException;
26 import org.apache.http.client.HttpClient;
27 import org.apache.http.client.entity.UrlEncodedFormEntity;
28 import org.apache.http.client.methods.HttpGet;
29 import org.apache.http.client.methods.HttpPost;
30 import org.apache.http.impl.client.DefaultHttpClient;
31 import org.apache.http.message.BasicNameValuePair;
32 import org.apache.http.params.BasicHttpParams;
33 import org.apache.http.params.HttpConnectionParams;
34 import org.apache.http.params.HttpParams;
35 import org.apache.http.util.EntityUtils;
36
37 import android.content.Context;
38 import android.net.ConnectivityManager;
39 import android.net.NetworkInfo;
40
41 public class NetWorkUtil {
42 public static final String LOGIN_URL = "http://101.200.142.201:8080/tqyb/login";
43 public static boolean isNetAvailable(Context context){
44 //获得网络管理器
45 ConnectivityManager connM =
46 (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
47 NetworkInfo netInfo = connM.getActiveNetworkInfo();//得到网络详情
48
49 if(netInfo == null || !netInfo.isAvailable())
50 return false;
51
52 return true;
53 }
54
55 public static String loginCheck_Get_HttpClient(String name,String pass,String url){
56 //通过StringBuffer来加工url
57 StringBuffer sb = new StringBuffer(url);
58 sb.append("?username=");
59 sb.append(name);
60 sb.append("&userpass=");
61 sb.append(pass);
62
63 String result = "";
64
65 HttpGet get = new HttpGet(sb.toString());//创建httpClient的get请求对象
66 //设置请求参数
67 HttpParams params = new BasicHttpParams();
68 HttpConnectionParams.setConnectionTimeout(params, 5*1000);
69 HttpConnectionParams.setSoTimeout(params, 5*1000);
70
71 HttpClient client = new DefaultHttpClient(params);//创建HttpClient对象
72
73 try {
74 HttpResponse res = client.execute(get);//执行请求,获得结果
75 if(res.getStatusLine().getStatusCode() == 200){
76 HttpEntity entity = res.getEntity();//获得相应结果,是一个HttpEntity对象
77 result = EntityUtils.toString(entity, "utf-8");//转换为字符串
78 }
79 } catch (ClientProtocolException e) {
80 // TODO Auto-generated catch block
81 e.printStackTrace();
82 } catch (IOException e) {
83 // TODO Auto-generated catch block
84 e.printStackTrace();
85 }
86 return result;
87
88 }
89
90 public static String loginCheck_POST_HttpClient(String name,String pass,String url){
91 String result = "";
92
93 HttpPost post = new HttpPost(url);//创建httpClient的post请求对象
94 //设置请求参数
95 HttpParams params = new BasicHttpParams();
96 HttpConnectionParams.setConnectionTimeout(params, 5*1000);
97 HttpConnectionParams.setSoTimeout(params, 5*1000);
98 //传值
99 //创建List集合,存放向服务器传递的数据
100 List<NameValuePair> reqData = new ArrayList<NameValuePair>();
101 NameValuePair p1 = new BasicNameValuePair("username", name);
102 NameValuePair p2 = new BasicNameValuePair("userpass", pass);
103 reqData.add(p1);
104 reqData.add(p2);
105
106 try {
107 HttpEntity entity = new UrlEncodedFormEntity(reqData, "utf-8");
108 post.setEntity(entity);//给post请求对象,设置上传的数据
109 HttpClient client = new DefaultHttpClient(params);//创建HttpClient对象
110 HttpResponse res = client.execute(post);//执行post请求,获得结果
111 if(res.getStatusLine().getStatusCode() == 200){
112 HttpEntity resEntity = res.getEntity();//获得相应结果,是一个HttpEntity对象
113 result = EntityUtils.toString(resEntity, "utf-8");//转换为字符串
114 }
115 } catch (UnsupportedEncodingException e1) {
116 // TODO Auto-generated catch block
117 e1.printStackTrace();
118 } catch (ClientProtocolException e) {
119 // TODO Auto-generated catch block
120 e.printStackTrace();
121 } catch (IOException e) {
122 // TODO Auto-generated catch block
123 e.printStackTrace();
124 }
125
126 return result;
127
128 }
129
130
131 }