Android网络请求之OkHttp框架

首先声明权限android

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

在build.gradle中加入api

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异步

 

Getide

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);
    }

Postpost

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);
                    }
                });
            }
        });
    }
相关文章
相关标签/搜索