码迷,mamicode.com
首页 > Web开发 > 详细

okhttp使用

时间:2017-06-30 21:09:44      阅读:312      评论:0      收藏:0      [点我收藏+]

标签:baidu   优化   oop   run   util   err   ring   log   pos   

okhttp是一种新的网络请求框架,对网络强求做了优化。

同步调用:

    public static String getStringByUrl(String url){
        try {
            initClient();
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    private void okhttpTest(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                final String url = "http://www.baidu.com";
                final String result = OkhttpUtils.getStringByUrl(url);
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }).start();
    }

异步调用:

    private void okhttpTest3(final Context context){
        final String url = "https://www.baidu.com";
        Request request = new Request.Builder()
                .url(url)
                .build();
        OkHttpClient client = new OkHttpClient();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, "Fail!", Toast.LENGTH_SHORT).show();
                    }
                });
            }
            @Override
            public void onResponse(Response response) throws IOException {
                final String result = response.body().string();
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

 

okhttp使用

标签:baidu   优化   oop   run   util   err   ring   log   pos   

原文地址:http://www.cnblogs.com/MiniHouse/p/7100418.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!