android的http请求get和post请求方式

本文详细介绍了如何使用HttpClient发起HTTP Get和Post请求,包括参数组装、请求发送及响应处理等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、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();

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值