HttpClient框架提交数据
HttpClient框架框架大大简化了手动写数据的提交,连接参数属性的设置已不需要我们操作,特别是POST提交参数,不用我们手动拼接那么麻烦。
//get 提交数据
public static String loginByClientGet(String username, String password){
try{
//1.打开一个浏览器
HttpClient client = new DefaultHttpClient();
//2.输入地址
String path = "http://192.168.1.110:8080/web/LoginServlet?username="
+ URLEncoder.encode(username)
+ "&password="
+ URLEncoder.encode(password);
HttpGet httpGet = new HttpGet(path);
//3.敲回车
HttpResponse response = client.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
if(code == 200){
InputStream is = response.getEntity().getContent();
String text = StreamTools.readInputStream(is);
return text;
}else{
return null;
}
}catch(Exception e){
e.printStackTrace;
return null;
}
}
//post 提交数据
public static String loginByClientPost(String username, String password){
try{
//1.打开一个浏览器
HttpClient client = new DefaultHttpClient();
//2.输入地址
String path = "http://192.168.1.110:8080/web/LoginServlet";
HttpPost httpPost = new HttpPost(path);
//指定要提交的数据实体
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
//3.敲回车
HttpResponse response = client.execute(httpPost);
int code = response.getStatusLine.getStatusCode();
if(code == 200){
InputStream is = response.getEntity().getContent();
String text = StreamTools.readInputStream(is);
return text;
}else{
return null;
}
}catch(Exception e){
e.printStackTrace();
return null;
}
}
点击事件:
public void click(View view){
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
new Thread(){
public void run(){
final String result = LoginService.loginByClientGet(username,password);
if(result != null){
runOnUiThread(new Runnable(){ //可直接移交给主线程操作
public void run(){
Toast.makeText(MainActivity.this, result, 0).show();
}
});
}else{
//请求失败
runOnUiThread(new Runnable(){ //可直接移交给主线程操作
public void run(){
Toast.makeText(MainActivity.this, "请求失败...", 0).show();
}
});
}
};
}.start();
}
post请求的点击事件同理.