为什么使用HttpClient?
如果用Android的URLConnection提交数据,设置很多参数非常麻烦,而且以post提交还需要抓包才能知道Content-type,非常不方便。所以用HttpClient,HttpClient是Apatch开源的,被google工程师直接拿到了Android下供开发者使用,以实体的形式返回数据和提交数据,是对URLConnection的封装
(根本没人用HttpClient 哈哈哈哈)
google工程师已经再API23(Android6.0)删除了HttpClient,用URLConnection替代
get方式请求
new Thread(){public void run() {
try {
String name = et_username.getText().toString().trim();
String pwd = et_password.getText().toString().trim();
//[2.1]定义get方式要提交的路径 小细节 如果提交中文要对name 和 pwd 进行一个urlencode 编码
String path = "http://192.168.11.73:8080/login/LoginServlet?username="+URLEncoder.encode(name, "utf-8")+"&password="+URLEncoder.encode(pwd, "utf-8")+"";
//[3]获取httpclient实例
DefaultHttpClient client = new DefaultHttpClient();
//[3.1]准备get请求 定义 一个httpget实现
HttpGet get = new HttpGet(path);
//[3.2]执行一个get请求
HttpResponse response = client.execute(get);
//[4]获取服务器返回的状态码
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
//[5]获取服务器返回的数据 以流的形式返回
InputStream inputStream = response.getEntity().getContent();
//[6]把流转换成字符串
String content = StreamTools.readStream(inputStream);
//[7]展示结果
showToast(content);
}
} catch (Exception e) {
e.printStackTrace();
}
};}.start();
post方式请求
new Thread(){public void run() {
try {
//[2]获取用户名和密码
String name = et_username.getText().toString().trim();
String pwd = et_password.getText().toString().trim();
String path = "http://192.168.11.73:8080/login/LoginServlet";
//[3]以httpClient 方式进行post 提交
DefaultHttpClient client = new DefaultHttpClient();
//[3.1]准备post 请求
HttpPost post = new HttpPost(path);
//[3.1.0]准备parameters
List<NameValuePair> lists = new ArrayList<NameValuePair>();
//[3.1.1]准备 NameValuePair 实际上就是我们要提交的用户名 和密码 key是服务器key :username
BasicNameValuePair nameValuePair = new BasicNameValuePair("username",name);
BasicNameValuePair pwdValuePair = new BasicNameValuePair("password",pwd);
//[3.1.3] 把nameValuePair 和 pwdValuePair 加入到集合中
lists.add(nameValuePair);
lists.add(pwdValuePair);
//[3.1.3]准备entity
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(lists);
//[3.2]准备post方式提交的正文 以实体形式准备 (键值对形式 )
post.setEntity(entity);
HttpResponse response = client.execute(post);
//[4]获取服务器返回的状态码
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
//[5]获取服务器返回的数据 以流的形式返回
InputStream inputStream = response.getEntity().getContent();
//[6]把流转换成字符串
String content = StreamTools.readStream(inputStream);
//[7]展示结果
showToast(content);
}
} catch (Exception e) {
e.printStackTrace();
}
};}.start();
总结:HttpClient是对URLConnection的封装,还是挺麻烦的 还要开子线程
网友评论