β

android - okhttp3 的用法 ( get, post ,异步... )

申思维的站点/Siwei's site 2 阅读

okhttp3 是目前来看android最火的 http组件.

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

发起get请求:

            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            try {

                Response response = okHttpClient.newCall(request).execute();
                String content = response.body().string();
                Log.d(TAG, "== url got: " + content.length());

//                writeHttpResponseToFile(url, response.body().string());

//                return new WebResourceResponse(getMimeTypeBySuffix(url), "utf-8", 
                     // 注意: 虽然这句代码可以把 string  转换成 inputStream  , 但是不要用它,会导致图片不显示
//                     new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));
                 //要用下面这句:         
                return new WebResourceResponse(getMimeTypeBySuffix(url), "utf-8", response.body().byteStream());
            }catch (IOException e){
                Log.e(TAG, "== got IOException");
                e.printStackTrace();
                return new WebResourceResponse(getMimeTypeBySuffix(url), "utf-8", null);
            }

务必记得:  response.body() 这个方法,   返回值只能取得一次,   也就是说, response.body().string() 只能做一次!

跟string() 类似的方法还有 .inputStream()等这样类似的读取内容的方法!  否则你会看到绝望的:

(参考: https://github.com/square/okhttp/issues/2683 )

IOException .... 

异步请求:

            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();

            client.newCall(request)
                    .enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            final String result = response.body().string();
                        }
                    });
作者:申思维的站点/Siwei's site
我是申思维,从事于WEB 和移动app开发 熟悉js (coffeescript), CSS, HTML,跟web相关的服务器(apache, nginx, passenger, mongrel, t
原文地址:android - okhttp3 的用法 ( get, post ,异步... ), 感谢原作者分享。

发表评论