网络请求框架(一):AsyncHttpClient

一使用场景

  1. 以get方式请求服务器
    1. 不带任何参数
    2. 带上key-value对
  2. 以post方式请求服务器
    1. 不带任何参数
    2. 带上key-value对
    3. 带上字节数组
    4. 带上文件
    5. 带上文件+key-value对
二.使用步骤,一get,和post为例

1.添加依赖

compile 'com.loopj.android:android-async-http:1.4.9'
2.get请求代码

 //get请求
    private void iniGet() {
        //创建请求对象
        AsyncHttpClient client=new AsyncHttpClient();
        //添加请求头
        client.addHeader("apikey","c8049d2f33ce7db72a33061efce748ba");
        //拿到路径
        String uri="http://apis.baidu.com/thinkpage/weather_api/suggestion";
        //创建请求参数
        RequestParams prams=new RequestParams();
       
        prams.put("location","beijing");
        //发送请求
        client.get(uri, prams, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                System.out.println(new String(responseBody));
                te.setText(new String(responseBody));
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                System.out.println("error======================");
            }
        });


    }

3.post请求代码

 //post请求
    private void iniPost() {
        //创建请求的对象
        AsyncHttpClient client =new AsyncHttpClient();
        //添加请求头
        client.addHeader("apikey","c8049d2f33ce7db72a33061efce748ba");
        //拿到请求地址
        String uri="http://apis.baidu.com/xiaogg/holiday/holiday";
        //创建请求参数
        RequestParams params =new RequestParams();
        params.put("d","20160909");
        //发送请求
        client.post(uri, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode==200){
                    System.out.println(new String(responseBody));
                    te.setText(new String(responseBody));
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                System.out.println("++++++++++error");
            }
        });

    }


你可能感兴趣的:(网络编程)