- httpclient实现get和post提交
- 代码实现过程
- 到包 compile ‘com.loopj.android:android-async-http:1.4.9’ 把这个包导入到build.gradle里
- httlclient实现get提交数据
private void httpclientGET() {
try {
String username = mName.getText().toString().trim();
String password = mPwd.getText().toString().trim();
String path = "http://192.168.0.156:8080/loginServlet/loginServlet?username=" + username + "&&password=" + password;
//使用httpclient提交数据
HttpClient client = new DefaultHttpClient();
//实现向服务器放松请求
HttpGet httpGet = new HttpGet(path);
HttpResponse httpResponse = client.execute(httpGet);
InputStream is = httpResponse.getEntity().getContent();
String content = StreamUtils.StreamToString(is);
showToast(content);
} catch (Exception e) {
e.printStackTrace();
}
}
private void httpclientPost() {
try {
String username = mName.getText().toString().trim();
String password = mPwd.getText().toString().trim();
String path = "http://192.168.0.156:8080/loginServlet/loginServlet";
//定义请求体
String data = "username=" + username + "&&password=" + password;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(path);
//定义请求体
List<NameValuePair> list = new ArrayList<>();
BasicNameValuePair nameValuePair = new BasicNameValuePair("username", username);
list.add(nameValuePair);
BasicNameValuePair passwordValuePair = new BasicNameValuePair("password", password);
list.add(passwordValuePair);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list);
post.setEntity(entity);
HttpResponse response = client.execute(post);
InputStream is = response.getEntity().getContent();
String content = StreamUtils.StreamToString(is);
showToast(content);
} catch (Exception e) {
e.printStackTrace();
}
}