okHttp3 Android开发Android技术知识

okHttp请求公共参数

2016-11-18  本文已影响3271人  白色相簿

othttp添加请求公共参数的几种方法

第一种 添加在请求链接尾部
HttpUrl url = original.url().newBuilder() //请求尾部链接
                    .addQueryParameter(VERSION, "")
                    .addQueryParameter(APP_VERSION, "")
                    .addQueryParameter(DEVICE, "")
                    .addQueryParameter(DEVICE_NAME, "android")
                    .addQueryParameter(DEVICE_IMEI, "")
                    .addQueryParameter(OS_VERSION, "")
                    .addQueryParameter(TOKEN, "")
                    .addQueryParameter(DEVICE_ID, "")
                    .build();

Request request = original.newBuilder()
                .method(original.method(), original.body())
                 //添加到请求里
                .url(url)
                .build();
第二种 添加在请求form表单里

最麻烦的一种,一般情况下不会用这种方法

RequestBody formBody = new FormBody.Builder()//form表单
                .add(DEVICE_ID, "")
                .add(CHANNEL, "")
                .add(DEVICE_SERIAL_ID, "")
                .add(MOBILE_OS, "android")
                .add(VERSION, "")
                .add(MEMBER_ID, "")
                .add(MEMBER_TYPE, "")
                .add(TOKEN, "")
                .build();

//默认添加formBody后不能添加新的form表单,需要先将RequestBody转成string去拼接
String postBodyString = bodyToString(original.body());
postBodyString += ((postBodyString.length() > 0) ? "&" : "") + bodyToString(formBody);

Request request = original.newBuilder()
                .method(original.method(), original.body())
                 //添加到请求里
                 //string转回成RequestBody
                .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),
                        postBodyString))
                .build();

RequestBody转String的方法

private static String bodyToString(final RequestBody request){
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if(copy != null)
                copy.writeTo(buffer);
            else
                return "";
            return buffer.readUtf8();
        }
        catch (final IOException e) {
            return "did not work";
        }
    }
第三种 添加在请求head
Request request = original.newBuilder()
                .method(original.method(), original.body())
                .addHeader(DEVICE_ID, "")
                .addHeader(CHANNEL, "")
                .addHeader(DEVICE_SERIAL_ID, "")
                .addHeader(MOBILE_OS, "android")
                .addHeader(VERSION, "")
                .addHeader(MEMBER_ID, "")
                .addHeader(TOKEN, "")
                .addHeader(MEMBER_TYPE, "")
                .build();
上一篇下一篇

猜你喜欢

热点阅读