一、Get请求
HttpClient介绍
HttpClient是用来模拟HTTP请求的,其实实质就是把HTTP请求模拟后发给Web服务器;
Android已经集成了HttpClient,因此可以直接使用;
注:此处HttpClient代码不只可以适用于Android,也可适用于一般的Java程序;
1.获取界面的请求参数
private HttpReaponse httpReaponse = null;
private HttpEntity httpEntity = null;
String name = nameView.getText().toString();
String age = ageView.getText().toString();
2.组装请求参数
String url = baseUrl + "?" +"name=" + name + "&age=" + age;
3.生成一个Get请求对象
HttpGet httpGet = new HttpGet(url);
4.生成Http客户端对象
HttpClient httpClient = new DefaultHttpClient();
4.使用Http客户端发送请求
//用来保存返回来的数据
InputStream inputStream = null;
try{
//模拟发送请求
httpResponse = httpClient.execute(httpGet);
//获取返回Entity
httpEntity = httpResponse.getEntity();
//获取返回内容
inputStream = heepEntity.getContent();
//读取返回内容
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String result = "";
String line = "";
while((line = reader.readLine()) != null){
result = result + line;
}catch (Exception e){
e.printStackTrace();
}
finally{
try{
inputStream.close();
}catch (Exception e)
{
e.printStackTrace();
}
}
}
二、Post请求
String name = nameView.getText().toString();
String age = ageView.getText().toString();
//把参数放到NameValuePair 里面以键值对的形式存在
NameValuePair valuea = new NameValuePair("name",name);
NameValuePair valueb = new NameValuePair("age",age);
//把参数加入到List集合当中
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(valuea);
list.add(valueb);
try{
//进行编码
HttpEntity requestHttpEntity = new UrlEncodeedFormEntity(list);
//生成Post请求对象
HttpPost httpPost = new HttpPost(baseUrl);
httpPost.setEntity(requestHttpEntity);
//生成http客户端对象
HttpClient httpClient = new DefaultHttpClient();
InputStream inputStream = null;
try{
httpResponse = httpClient.excute(httpPost);
//获取返回Entity
httpEntity = httpResponse.getEntity();
//获取返回内容
inputStream = heepEntity.getContent();
//读取返回内容
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String result = "";
String line = "";
while((line = reader.readLine()) != null){
result = result + line;
}catch (Exception e){
e.printStackTrace();
}
finally{
try{
inputStream.close();
}catch (Exception e)
{
e.printStackTrace();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}