android HTTP中的两种形式HttpURLConnection和ApacheHTTP,上一篇介绍的是HttpURLConnection,通过url形式传递参数,ApacheHTTP使得HTTP编程更加简单高效。在上一遍的基础上把客户端的登陆请求用Apache HTTP来写。
public void ApacheHttp(String name, String password) {
String urlStr = "http://192.168.1.101:8080/MyServer/servlet/LoginServlet";
// 用HttpPost来提交参数
HttpPost post = new HttpPost(urlStr);
// 参数比较多的话,对参数进行封装
List<NameValuePair> paras = new ArrayList<NameValuePair>();
// 添加用户名和密码
paras.add(new BasicNameValuePair("name", name));
paras.add(new BasicNameValuePair("password", password));
try {
//设置请求参数
post.setEntity(new UrlEncodedFormEntity(paras,HTTP.UTF_8));
//执行请求相应
HttpResponse response = new DefaultHttpClient().execute(post);
if(response.getStatusLine().getStatusCode()==200){
String msg=EntityUtils.toString(response.getEntity());
AlertDialog.Builder build = new AlertDialog.Builder(this);
build.setMessage(msg).setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
});
AlertDialog alert = build.create();
alert.show();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}