Android网络请求之OkHttp框架

首先声明权限

<uses-permission android:name="android.permission.INTERNET"/>

在build.gradle中加入

compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.okio:okio:1.5.0'

API接口:https://www.juhe.cn/docs/api/id/46

Get

复制代码
public void okHttpGet(){
        //构造一个Request对象,参数最起码有个url,
        // 当然你可以通过Request.Builder设置更多的参数比如:header、method等。
        final Request request = new Request.Builder()
                .url(COOK_URL_GET + "key=" + COOK_KEY + "&menu=" + MENU)
                .build();
        getResponse(request);
    }
复制代码

Post

复制代码
private void okHttpPostCook() {
        RequestBody body = new FormEncodingBuilder()
                .add("menu", MENU)
                .add("key", COOK_KEY)
                .build();
        //构造一个Request对象,参数最起码有个url,
        // 当然你可以通过Request.Builder设置更多的参数比如:header、method等。
        final Request request = new Request.Builder()
                .url(COOK_URL_POST)
                .post(body)
                .build();
        getResponse(request);
    }
复制代码
getResponse
复制代码
public void getResponse(Request request){
        //创建okHttpClient对象
        OkHttpClient mOkHttpClient = new OkHttpClient();
        //通过request的对象去构造得到一个Call对象,类似于将你的请求封装成了任务,
        // 既然是任务,就会有execute()和cancel()等方法
        Call call = mOkHttpClient.newCall(request);
        //以异步的方式去执行请求,所以我们调用的是call.enqueue,将call加入调度队列,
        // 然后等待任务执行完成,我们在Callback中即可得到结果。
        call.enqueue(new Callback()
        {
            @Override
            public void onFailure(Request request, IOException e)
            {
                Toast.makeText(MainActivity.this, "onFailure", Toast.LENGTH_SHORT);
            }
            @Override
            public void onResponse(final Response response) throws IOException
            {
                final String responseJSON =  response.body().string();
                //onResponse执行的线程并不是UI线程,如果你希望操作控件,还是需要使用handler等
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        tv.setText(responseJSON);
                    }
                });
            }
        });
    }

from: https://www.cnblogs.com/mycd/p/5706167.html

猜你喜欢

转载自www.cnblogs.com/GarfieldEr007/p/10016727.html