<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">HttpClient是由Apache提供的一个完善的支持HTTP协议的编程工具包。虽然它提供了对HTTP协议的全面支持,但是开发者只可以使用http协议中的get和post两种请求方式。</span>
HttpClient的一般使用步骤如下:
1.创建一个HttpClient对象,因为HttpClient是一个接口,并且有很多方法,所以一般使用系统提供一个简单类,DefaultHttpClient
2.实例化Http方法,比如HttpPost,HttpGet。
3.设置Http参数。此处注意:因为get请求的参数是写在url中的,在传递时,是将参数封装到http协议的请求头中。而post请求的参数必须要单独写出来,并且是封装到http协议体中的(注意:无论是get还是post,在网络传输参数之前,都要对参数进行URL编码)。所以此处的设置Http参数对于post请求而言更为特殊。
HttpClient提供了NameValuePair(名/值对,也就是传说中的键值对)来封装参数。 并且还需要使用UrlEncodeFormEntity对NameValuePair来进行Url编码,之后才可以设置到请求体中。
4.使用HttpClient执行请求,即HttpClient调用execute方法。
5.处理Http响应,即处理execute方法的返回值。
HttpClient执行get请求:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
HttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet("http://localhost:8080/userServlet?name=wangwu");
HttpResponse response;
InputStream in = null;
BufferedReader br = null;
try {
response = httpClient.execute(request);
in = response.getEntity().getContent();
br = new BufferedReader(new InputStreamReader(in));
String info;
while((info = br.readLine()) != null){
Log.i("HttpGet",info);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (br != null)
br.close();
if (in != null)
in.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}).start();
}
HttpClient执行 post请求
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
new Thread(new Runnable() {
@Override
public void run() {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://localhost:8080/userServlet");
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("name","wangyili"));
postParameters.add(new BasicNameValuePair("address","China"));
postParameters.add(new BasicNameValuePair("age","22"));
InputStream in = null;
BufferedReader br = null;
try {
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
httpPost.setEntity(formEntity);
HttpResponse response = null;
response = httpClient.execute(httpPost);
in = response.getEntity().getContent();
br = new BufferedReader(new InputStreamReader(in));
String info;
while((info = br.readLine()) != null){
Log.i("HttpPost", info);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (br != null)
br.close();
if (in != null)
in.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}).start();
}