前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用Retrofit打印请求日志,过滤改变服务器返回结果,直接获取String字符串直接获取字符串手动解析查看Retrofit请求网络日志自定义Interceptor实现过滤改变请求返回的数据(可使用

使用Retrofit打印请求日志,过滤改变服务器返回结果,直接获取String字符串直接获取字符串手动解析查看Retrofit请求网络日志自定义Interceptor实现过滤改变请求返回的数据(可使用

作者头像
Xiaolei123
发布2018-06-28 12:04:05
3.9K0
发布2018-06-28 12:04:05
举报

Retrofit框架越来越流行了,Retrofit是基于OKHTTP的大家都知道,在之前的话,在Retrofit1.x的时候,是必须要自己手动导入OKHTTP 和 OKio的包的,因为Retrofit依赖于这两个库的。但是自从升级了Retrofit2之后,就可以不用手动导入了,因为已经自己引入了。

Retrofit有一个优点,就是可以自动根据获取到的数据转换成相对应的Bean,它内部提供了一个转换机制,只需要你重写,就能写出自己的转换规则。

dependencies {
    compile 'com.squareup.retrofit2:retrofit:2.2.0'
    compile 'com.squareup.retrofit2:converter-scalars:2.0.0'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    }

可以看到,我上面引入了Retrofit2的库

compile 'com.squareup.retrofit2:retrofit:2.2.0' 但是除了这个份之外,我还引入了其他的。

这两个,是在从请求Json数据到Bean需要使用到的。依赖了谷歌的Gson库

compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.google.code.gson:gson:2.7'

直接获取字符串手动解析

除了这种情况,我们经常会因为后台传来的数据的不稳定性,我们需要自己手动去解析字符串,那么就引入了这个 compile 'com.squareup.retrofit2:converter-scalars:2.0.0'

使用方式好简单:

new Retrofit.Builder()  //01:获取Retrofit对象
.baseUrl(Globals.SERVER_ADDRESS) //02采用链式结构绑定Base url
.addConverterFactory(ScalarsConverterFactory.create())//首先判断是否需要转换成字符串,简单类型
.addConverterFactory(GsonConverterFactory.create())//再将转换成bean
.client(okHttpClient)
.build();//03执行操作
public interface StartPageNet
{
    @GET("hao123-soft-online-bcs/soft/2017_02_22_W.P.S.5041.19.552.exe")
    public Call<String> getIndex();
}

首先在这里定义,Call<String> 里的泛型可以写这几种类型:

if (type == String.class
        || type == boolean.class
        || type == Boolean.class
        || type == byte.class
        || type == Byte.class
        || type == char.class
        || type == Character.class
        || type == double.class
        || type == Double.class
        || type == float.class
        || type == Float.class
        || type == int.class
        || type == Integer.class
        || type == long.class
        || type == Long.class
        || type == short.class
        || type == Short.class) {
      return ScalarRequestBodyConverter.INSTANCE;
    }

这里会自动根据返回数据转换成你泛型里写的类型的数据。

 StartPageNet startPageNet = streamRetrofit.create(StartPageNet.class);
 Call<String> download = startPageNet.getIndex();
 download.enqueue(new Callback<String>()
 {
     @Override
     public void onResponse(Call<String> call, Response<String> response)
     {
         String result = response.body();
     }
     @Override
     public void onFailure(Call<String> call, Throwable t)
     {

     }
});

查看Retrofit请求网络日志

有时候需要随时查看网络请求日志,我们这里可以利用OKHttpInterceptor机制 上面我们引入了这个库: compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

使用代码如下:

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger()
{
     @Override
     public void log(String message) 
     {
         if (BuildConfig.DEBUG) Log.d("Http", message+"");
     }
});
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);//设置日志打印等级
        
 OkHttpClient  okHttpClient = new OkHttpClient.Builder()             
         .addInterceptor(loggingInterceptor)//设置日志打印
         .retryOnConnectionFailure(true)//失败重连
         .connectTimeout(30, TimeUnit.SECONDS)//网络请求超时时间单位为秒
         .build();

.addInterceptor()可以调用多次

自定义Interceptor实现过滤改变请求返回的数据(可使用与保证APP的稳定性)

import com.alibaba.fastjson.JSON;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSource;
import okio.Okio;

/**
 * 网络请求的拦截器
 * Created by xiaolei on 2017/3/2.
 */

public class SessionInterceptor implements Interceptor
{
    @Override
    public Response intercept(Chain chain) throws IOException
    {
        Request request = chain.request();
        Response response = chain.proceed(request);
        return new Response.Builder()
                .body(newResponseBody(response))
                .headers(response.headers())
                .message(response.message())
                .code(response.code())
                .request(response.request())
                .protocol(response.protocol())
                .build();
    }
    private ResponseBody newResponseBody(final Response response)
    {
        return new ResponseBody()
        {
            @Override
            public MediaType contentType()
            {
                return response.body().contentType();
            }
            @Override
            public long contentLength()
            {
                return response.body().contentLength();
            }
            @Override
            public BufferedSource source()
            {
                try
                {
                    String result = response.body().string();
                    if(JSON.parseObject(result).getInteger("code") == 500)
                    {
                        /**
                        *这里改变返回的数据,如果服务器返回的是一个HTML网页,
                        *那么移动端也能拿到一个Json数据,用于保证数据可解析不至于崩溃
                        */
                        ByteArrayInputStream tInputStringStream = new ByteArrayInputStream("{code:500,success:false}".getBytes());
                        BufferedSource source = Okio.buffer(Okio.source(tInputStringStream));
                        return source;
                    }else
                    {
                        ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(result.getBytes());
                        BufferedSource source = Okio.buffer(Okio.source(tInputStringStream));
                        return source;
                    }
                } catch (IOException e)
                {
                    e.printStackTrace();
                    return null;
                }
            }
        };
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.11.17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 直接获取字符串手动解析
  • 查看Retrofit请求网络日志
  • 自定义Interceptor实现过滤改变请求返回的数据(可使用与保证APP的稳定性)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档