HttpClient
的使用HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。
使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。
Get请求使用方法
public void get(View view) {
new Thread() {
public void run() {
try {
// 创建请求发送对象HttpClient
HttpClient client = new DefaultHttpClient();
// 创建get
String url = "http://www.baidu.com";
HttpGet get = new HttpGet(url);
// 服务端返回数据
HttpResponse response = client.execute(get);// 发送 没有封装线程的对象
// 就不需要回调
InputStream input = response.getEntity().getContent();
byte[] data = StreamUtils.readInputStream(input);
String result = new String(data, "utf-8");
Log.i("wzx", result);
input.close();
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
Psot()
public void post(View view) {
new Thread() {
public void run() {
try {
// 创建请求发送对象HttpClient
HttpClient client = new DefaultHttpClient();
// 创建post
String url = "http://192.168.32.10:8080/web/LoginServlet";
HttpPost post = new HttpPost(url);
// 变量 NameValuePair:Map.Entry
NameValuePair username = new BasicNameValuePair("username", "中国ujj");
NameValuePair passowrd = new BasicNameValuePair("password", "中国ujj");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(username);
params.add(passowrd);
UrlEncodedFormEntity form = new UrlEncodedFormEntity(params, "utf-8");
post.setEntity(form);// 添加表单到请求里,带到服务端
// 服务端返回数据
HttpResponse response = client.execute(post);// 发送 没有封装线程的对象
InputStream input = response.getEntity().getContent();
byte[] data = StreamUtils.readInputStream(input);
String result = new String(data, "utf-8");
Log.i("wzx", result);
input.close();
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
原文:http://www.cnblogs.com/ganwei/p/4888642.html