β

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

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

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

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

发起get请求:

            
        OkHttpClient okHttpClient = new OkHttpClient();

        //这里这么啰嗦,是为了添加一个参数: device_model 
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        urlBuilder.addQueryParameter("device_model", "Sumsang s3");
        HttpUrl finalUrl  = urlBuilder.build();

        Request request = new Request.Builder()
                .url(finalUrl)
                .get()
                .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();
                        }
                    });

发起POST异步请求:

        // 再告诉远程服务器,已经解绑了
        OkHttpClient httpClient = new OkHttpClient();
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("token", token)
                .build();

        String url = PageUrls.UNBIND_DEVICE;
        Log.d(TAG, "== unbind url: " + url);
        Request request = new Request.Builder().
                url(url)
                .post(requestBody)
                .build();

        httpClient.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 {
                        String response_result = response.body().string();
                        Log.d(TAG, "== unbind device, response: " + response_result);
                        try {
                            JSONObject json = new JSONObject(response_result);
                            if(json.getString("result").equals("Ok")){
                                Message msg = Message.obtain();
                                msg.what = Constants.SUCCESSFULLY_UNBINDED;
                                msg.obj = getResources().getString(R.string.successfully_unbinded);
                                handler.sendMessage(msg);
                            }
                        } catch (JSONException e) {
                            Message msg = Message.obtain();
                            msg.what = Constants.SERVER_ERROR;
                            msg.obj = getResources().getString(R.string.global_error_messsage_from_yunbi_server);
                            handler.sendMessage(msg);
                            e.printStackTrace();
                        }


                    }
                });

 
作者:申思维的站点/Siwei's site
我是申思维,从事于WEB 和移动app开发 熟悉js (coffeescript), CSS, HTML,跟web相关的服务器(apache, nginx, passenger, mongrel, t
原文地址:android - okhttp3 的用法 ( get, post ,异步... ), 感谢原作者分享。

发表评论