public class HttpURLConnectionActivity extends ActionBarActivity {
private TextView tv_info;
private EditText et_username,et_password;
private static final int LOAD_SUCESS = 200;
private static final int LOAD_ERROR = -1;
private final MyHandler handler = new MyHandler(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_urlconnection);
tv_info = (TextView) findViewById(R.id.info);
et_username = (EditText) findViewById(R.id.editText_username);
et_password = (EditText) findViewById(R.id.editText2_password);
}
private static class MyHandler extends Handler {
private final WeakReference<HttpURLConnectionActivity> weakReference;
public MyHandler(HttpURLConnectionActivity activity){
weakReference = new WeakReference<HttpURLConnectionActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
HttpURLConnectionActivity activity = weakReference.get();
if(activity!=null){
switch (msg.what){
case LOAD_SUCESS:
String json = (String) msg.obj;
activity.jsonToObject(json);
break;
case LOAD_ERROR:
activity.tv_info.setText("登录失败,请检查用户名或密码是否正确!");
break;
}
}
}
}
//解析JSON为对象
public void jsonToObject(String json){
Gson gson = new Gson();
JsonObject object = gson.fromJson(json, JsonObject.class);
tv_info.setText(object.toString());
}
/**
* 登录功能
* @param view
*/
public void loginClick(View view){
final String username = et_username.getText().toString();
if(TextUtils.isEmpty(username)){
Toast.makeText(this,"用户名不能为空",Toast.LENGTH_SHORT).show();
return;
}
final String password = et_password.getText().toString();
if(TextUtils.isEmpty(password)){
Toast.makeText(this,"密码不能为空",Toast.LENGTH_SHORT).show();
return;
}
System.out.println("name and password not null");
//启动登录工作线程
new Thread(new Runnable() {
@Override
public void run() {
String path = "http://10.0.2.2:8080/Android_NetServer/LoginServlet";
try {
System.out.println(path);
URL url = new URL(path);
//打开http连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(1000 * 30);//连接超时时间
conn.setReadTimeout(1000 * 30);//读数据的超时时间
conn.setUseCaches(false);
conn.setRequestProperty("content-type","application/x-www-form-urlencoded");
//对服务器端读取或写入数据(使用输入输出流)
//获取连接的输出流
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes("username=" + URLEncoder.encode("vince", "GBK"));
out.writeBytes("&password=" + URLEncoder.encode("123", "GBK"));
out.flush();
out.close();
//从服务器获取响应数据
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String result = br.readLine();
System.out.println("result=" + result);
br.close();
conn.disconnect();//关闭连接
Message msg = handler.obtainMessage(LOAD_SUCESS,result);
handler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
handler.sendEmptyMessage(LOAD_ERROR);
}
}
}).start();
}