HttpClient简单使用:
首先:Apache官网下载 HttpClient,需要了解三个类
HttpClient 代表Http客户端 里面定义了很多http 请求执行行为
HttpEntity 消息载体,发送或者接收消息的载体,可以通过客户端请求或者服务器响应获取实例
HttpConnection 代表http连接
直接上代码,备注中有解释,关键现在HttpClient谷歌官方已经不怎么推荐了(Android2.3之前有一个bug,不过还是封装的挺号用的。):
HttpGet:
public void httpGet() {
try {
/***要了解的三个类
* HttpClient 代表Http客户端
HttpEntity 消息载体,发送或者接收消息的载体,可以通过客户端请求或者服务器响应获取实例
HttpConnection 代表http连接
**/
// 创建默认的客户端实例
HttpClient httpClient = new DefaultHttpClient();
String url = "http://www.baidu.com";
//HttpGet也可以带参数的:url + "?bookname=" + etBookName.getText().toString();
// 创建get请求实例
HttpGet httpGet = new HttpGet(url);
// 客户端执行get请求 返回响应实体
HttpResponse httpResponse = httpClient.execute(httpGet);
//获得输入流,用BufferedReader包装
BufferedReader in = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
StringBuilder stringBuilder = new StringBuilder();
String lines = null;
//将内容写入StringBuilder中
while ((lines = in.readLine()) != null) {
lines = new String(lines.getBytes("UTF-8"));
stringBuilder.append(lines);
}
in.close();
Log.e("StringBuidler的值", stringBuilder.toString());
showToast(stringBuilder.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
HttpPost:
public void httpPost() {
String url = "http://www.baidu.com";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
//创建请求的参数,这里与HttpGet不同
List<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("username", name.getText().toString()));
list.add(new BasicNameValuePair("password", pass.getText().toString()));
try {
//url格式编码,解析成一个entity对象
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//设置请求内容
httpPost.setEntity(uefEntity);
//执行请求
try {
//使用客户端向服务器发送数据,获得返回值
HttpResponse httpResponse = httpClient.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
StringBuilder stringBuilder = new StringBuilder();
String lines = null;
//将内容写入StringBuilder中
while ((lines = in .readLine()) != null) {
lines = new String(lines.getBytes("UTF-8"));
stringBuilder.append(lines);
}
in .close();
Log.e("StringBuidler的值", stringBuilder.toString());
showToast(stringBuilder.toString());
} catch (IOException e) {
e.printStackTrace();
}
}