andorid 通信 HttpClient接口

 2.HttpClient接口

代码:    

/设置/url

String httpUrl = "http://10.0.2.2/****" ;

//HttpGet对象获取

HttpGet httpRequest = new HttpGet(httpUrl);

try{

    //HttpClient对象获取

    HttpClient httpClient = enw DefaultHttpClient();

    //请求httpClient,取得response

    HttpResponse httpResponse = httpClient.execute(httpRequest);

    //请求成功

    if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){

        //获取数据

        String result = EntityUtils.toString(httpResponse.getEntity());

    }

}catch(Exception e){}  //ClientProtocol IOException


POST:需要使用NameValuePair来保存数据,BaseNameValuePair构造被传递数据参数,add方法添加到NameValuePair

/设置/url

String httpUrl = "http://10.0.2.2/****" ;


//HttpGet对象获取

HttpPost httpRequest = new HttpPost(httpUrl);

//使用 NameValuePair保存需要传递的数据

List<NameValuePair> parmas = new ArrayList<NameValuePair>();

//添加需要传递的数据

params.add(new BaseNameValuePair("str","hello world"));


try{


    ​//设置字符集

    ​ HttpEntity httpEntity = new UrlEncodedFormEntity(params,"fb2312");

    ​//请求默认的HttpRequest

    ​httpRequest.setEntity(httpEntity);

   

    ​ //HttpClient对象获取

    HttpClient httpClient = enw DefaultHttpClient();

    //请求httpClient,取得response

    HttpResponse httpResponse = httpClient.execute(httpRequest);

    //请求成功

    if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){

        //获取数据

        String result = EntityUtils.toString(httpResponse.getEntity());

    }

}catch(Exception e){}  //ClientProtocol IOException

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tobin liao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值