设置接口如下:
- 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";
- }
- }
出处http://blog.csdn.net/honghailiang888。