android:http

本文详细介绍了如何使用org.apache.http库进行HTTP请求,包括GET和POST方式的实现,并提供了关键代码示例。重点突出HTTP客户端的创建、请求发送及文件流操作过程,适合初学者快速掌握HTTP请求的基础。

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

使用org.apache.http

//生成一个请求对象
HttpGet httpGet = new HttpGet("http://www.baidu.com");
//生成一个Http客户端对象
HttpClient httpClient = new DefaultHttpClient();
//使用Http客户端发送请求对象
InputStream inputStream = null;
try {
    httpResponse = httpClient.execute(httpGet);
    httpEntity = httpResponse.getEntity();
    inputStream = httpEntity.getContent();
    //文件流操作
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    String result = "";
    String line = "";
//  StringBuilder builder = new StringBuilder();
  
while((line = reader.readLine()) != null){ result = result + line;
// builder.append(s); } System.out.println(result); }
catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try{ inputStream.close(); } catch(Exception e){ e.printStackTrace(); } } }
/*  JSONObject jsonObject = new JSONObject(builder.toString());
        String re_username = jsonObject.getString("username");
        String re_password = jsonObject.getString("password");
        int re_user_id = jsonObject.getInt("user_id");
*/

GET和POST方式:

GET:即在baseUrl后“ ?”  “ &”加一些参数即可

POST方式:

NameValuePair nameValuePair1 = new BasicNameValuePair("name",name); //name为读取的值  
NameValuePair nameValuePair2 = new BasicNameValuePair("age",age); //age为读取的值  
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
nameValuePairs.add(nameValuePair1);  
nameValuePairs.add(nameValuePair2);  
//生成Entity对象  
HttpEntity requestHttpEntity = new UrlEncodedFormEntity(nameValuePairs);  
HttpPost httpPost = new HttpPost(url); //这里的url是baseUrl 不用拼上?key=value...  
httpPost.setEntity(requestHttpEntity );  
//之后的操作一样  

 

 

 

转载于:https://www.cnblogs.com/mybkn/archive/2012/05/18/2508400.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值