【Android-010】【HttpClient使用】

来源:互联网 发布:淘宝代销保证金能退吗 编辑:程序博客网 时间:2024/05/16 05:04

Android学习目录


项目源码下载


HttpClient

发送get请求

  • 创建一个客户端对象
    HttpClient client = new DefaultHttpClient();
  • 创建一个get请求对象
    HttpGet hg = new HttpGet(path);
  • 发送get请求,建立连接,返回响应头对象
    HttpResponse hr = hc.execute(hg);
  • 获取状态行对象,获取状态码,如果为200则说明请求成功
        if(hr.getStatusLine().getStatusCode() == 200){            //拿到服务器返回的输入流            InputStream is = hr.getEntity().getContent();            String text = Utils.getTextFromStream(is);        }

发送post请求

        //创建一个客户端对象        HttpClient client = new DefaultHttpClient();        //创建一个post请求对象        HttpPost hp = new HttpPost(path);
  • 往post对象里放入要提交给服务器的数据
        //要提交的数据以键值对的形式存在BasicNameValuePair对象中        List<NameValuePair> parameters = new ArrayList<NameValuePair>();        BasicNameValuePair bnvp = new BasicNameValuePair("name", name);        BasicNameValuePair bnvp2 = new BasicNameValuePair("pass", pass);        parameters.add(bnvp);        parameters.add(bnvp2);        //创建实体对象,指定进行URL编码的码表        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");        //为post请求设置实体        hp.setEntity(entity);

异步HttpClient框架

AsyncHttpClient地址:https://github.com/AsyncHttpClient/async-http-client

发送get请求

        //创建异步的httpclient对象        AsyncHttpClient ahc = new AsyncHttpClient();        //发送get请求        ahc.get(path, new MyHandler());
  • 注意AsyncHttpResponseHandler两个方法的调用时机
        class MyHandler extends AsyncHttpResponseHandler{            //http请求成功,返回码为200,系统回调此方法            @Override            public void onSuccess(int statusCode, Header[] headers,                    //responseBody的内容就是服务器返回的数据                    byte[] responseBody) {                Toast.makeText(MainActivity.this, new String(responseBody), 0).show();            }            //http请求失败,返回码不为200,系统回调此方法            @Override            public void onFailure(int statusCode, Header[] headers,                    byte[] responseBody, Throwable error) {                Toast.makeText(MainActivity.this, "返回码不为200", 0).show();            }        }

发送post请求

  • 使用RequestParams对象封装要携带的数据
        //创建异步httpclient对象        AsyncHttpClient ahc = new AsyncHttpClient();        //创建RequestParams封装要携带的数据        RequestParams rp = new RequestParams();        rp.add("name", name);        rp.add("pass", pass);        //发送post请求        ahc.post(path, rp, new MyHandler());
1 1
原创粉丝点击