关于HttpClient详细学习资料的博客
依赖
useLibrary 'org.apache.http.legacy'
HttpClient简单操作的大致步骤:
1. 创建HttpClient对象。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求, 创建HttpPost对象。
3. 如果需要发送请求参数,HttpGet的话在url之后加上?连接参数;对于HttpPost对象而言,可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;
调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
HttpClient中get请求
butget.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//获取输入框里面输入的数据
ename = edone.getText().toString();
epwd = edtwo.getText().toString();
//定义访问网址和要查询的数据
final String pathget = "http://123.206.70.44:8080/JavaWebTest/Upload_html?user=" + ename + "&password=" + epwd;
//开启子线程 进行访问网络
new Thread() {
@Override
public void run() {
// 1、创建httpclient对象
DefaultHttpClient httpClient = new DefaultHttpClient();
// 2、创建网络请求的方式
HttpGet httpGet = new HttpGet(pathget);
// 将对请求方式添加到对象中 获得相应头
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine line = response.getStatusLine();
int code = line.getStatusCode();
if (code == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
final String textFromStream = Tools.getTextFromStream(content);
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
tvclient.setText(textFromStream);
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
});
HttpClient中的post请求
//添加post请求方式
butpost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String pathpost = "http://123.206.70.44:8080/JavaWebTest/Upload_html?";
ename = edone.getText().toString();
epwd = edtwo.getText().toString();
new Thread() {
@Override
public void run() {
//创建对象并且添加post路径
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(pathpost);
//把要提交的数据封装到post请求中
BasicNameValuePair user = new BasicNameValuePair("user", ename);
BasicNameValuePair password = new BasicNameValuePair("password", epwd);
//创建一个集合 封装提交的数据
ArrayList<NameValuePair> list = new ArrayList<>();
list.add(user);
list.add(password);
//创建实体封装提交的数据
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "utf-8");
//封装到post请求里面
httpPost.setEntity(entity);
try {
HttpResponse response = httpClient.execute(httpPost);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream inputStream = response.getEntity().getContent();
final String fromStream = Tools.getTextFromStream(inputStream);
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
tvclient.setText(fromStream);
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}.start();
}
});