1. 程式人生 > >【Android實戰】----Android Retrofit2.1.0設定編碼格式GBK

【Android實戰】----Android Retrofit2.1.0設定編碼格式GBK

設定介面如下:

public interface IHttpService {

    /**
     * 獲取userId
     * @param params
     * @return
     */
    @FormUrlEncoded
    @POST("user/userid.do")
    Call<UserIdBean> getUserById(@FieldMap(encoded = true) Map<String, String>params);

    /**
     * 獲取userId
     * @param params
     * @return
     */
    @FormUrlEncoded
    @POST("user/login.do")
    Call<UserBean> login(@FieldMap(encoded = true) Map<String, String>params);

}

retrofit中@FormUrlEncoded的預設編碼方式為UTF-8,這個沒法改變(目前本人所知,如有誤請賜教微笑),那麼可以通過MediaType進行設定

/**
     * 新增統一header,超時時間,http日誌列印
     * @return
     */
    public static OkHttpClient genericClient() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        Request.Builder requestBuilder = request.newBuilder();
                        request = requestBuilder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=GBK"),
                                URLDecoder.decode(bodyToString(request.body()), "UTF-8")))
                                .build();
                        return chain.proceed(request);
                    }
                })
                .addInterceptor(logging)
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .build();
              return httpClient;
           }
如上設定了
"application/x-www-form-urlencoded;charset=GBK"

但是request.body()獲取到的是已經是經過@FormUrlEncoded編碼(UTF-8)過的,因此要先用UTF-8解碼,再用GBK編碼

bodyToString()的實現

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