RoboSpice - 没有获取缓存数据

时间:2017-03-16 11:07:46

标签: android robospice

我正在使用RoboSpice进行网络服务调用,如下所示。

spiceManager.execute(request, lastRequestCacheKey,
                DurationInMillis.ONE_DAY, this);

每次都是Bu,它使用loadDataFromNetwork()发出网络请求。

似乎缓存数据为空。收到此消息"Cache content not available or expired or disabled"

我做错了什么?

1 个答案:

答案 0 :(得分:0)

解决。对于寻找相同内容的人,请阅读。

  • https://www.npmjs.com/package/typedcontract开始,它应该为每个Web服务请求创建自定义请求(SpringAndroidSpiceRequest;基于Model对象)。
  • 但我有很多服务请求&不同的模型类。所以,如果我们为每个模型创建单独的请求,代码结构将变得混乱。
  • 因此,创建了通用请求
  • 但是,我无法从缓存中获取数据。只需覆盖getResultType()

    @Override
    public Class<Object> getResultType() {
        return (Class<Object>) clazz;
    }
    

这是完整的代码。

public class WebServiceRequest extends SpringAndroidSpiceRequest<Object> {

private String url;
private int TIMEOUT_TIME = 15000;
Class<?> clazz;
HTTPMethod httpMethod;
private MultiValueMap multiValueMap;

public WebServiceRequest(HTTPMethod httpMethod, String Token, String url, Class<?> clazz, @Nullable MultiValueMap multiValueMap) {
    super(Object.class);
    this.httpMethod = httpMethod;
    this.token = Token;
    this.url = url;
    this.clazz = clazz;
    this.multiValueMap = multiValueMap;
}

@Override
public Object loadDataFromNetwork() {
    Object response = null;
    try {
        if (this.httpMethod == HTTPMethod.GET) {
            Uri.Builder uriBuilder = Uri.parse(this.url).buildUpon();
            String urls = uriBuilder.build().toString();
            response = getRestTemplate().getForObject(urls, clazz);
        } else {
            RestTemplate restTemplate = new RestTemplate(true);
            restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
            restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
            restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity<?> requestEntity = new HttpEntity<Object>(this.multiValueMap, requestHeaders);
            // Test URL : http://posttestserver.com/post.php  
            response = restTemplate.postForObject(this.url, requestEntity, clazz);
        }
        manageTimeOuts(getRestTemplate());
        return response;
    } catch (Exception timeoutException) {
        return response;
    }

}

@Override
public Class<Object> getResultType() {
    return (Class<Object>) clazz;
}

private void manageTimeOuts(RestTemplate restTemplate) {
    // set timeout for requests
    ClientHttpRequestFactory factory = restTemplate.getRequestFactory();
    if (factory instanceof HttpComponentsClientHttpRequestFactory) {
        HttpComponentsClientHttpRequestFactory advancedFactory = (HttpComponentsClientHttpRequestFactory) factory;
        advancedFactory.setConnectTimeout(TIMEOUT_TIME);
        advancedFactory.setReadTimeout(TIMEOUT_TIME);
    } else if (factory instanceof SimpleClientHttpRequestFactory) {
        SimpleClientHttpRequestFactory advancedFactory = (SimpleClientHttpRequestFactory) factory;
        advancedFactory.setConnectTimeout(TIMEOUT_TIME);
        advancedFactory.setReadTimeout(TIMEOUT_TIME);
    }
}

public String createCacheKey() {
    return clazz.getName() + token;
}

}

启动Web服务请求并获取响应回调,如下所示。

public class HomeActivity extends AppCompatActivity implements RequestListener<Object> {

    private SpiceManager spiceManager = new SpiceManager(
            JacksonSpringAndroidSpiceService.class);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        String url = "http://192.168.56.1:8080/JSONRestWebServiceExample/JavaCodeGeeks/AuthorService/authors";
        WebServiceRequest request = new WebServiceRequest(HTTPMethod.GET, null, url, new ArrayList<Model>().getClass(), null);    
        String lastRequestCacheKey = request.createCacheKey();
        spiceManager.execute(request, lastRequestCacheKey,
                DurationInMillis.ONE_DAY, this);
    }

    @Override
    protected void onStart() {
        spiceManager.start(this);
        super.onStart();
    }

    @Override
    protected void onStop() {
        spiceManager.shouldStop();
        super.onStop();
    }

    @Override
    public void onRequestSuccess(Object object) {
        ObjectMapper objectMapper = new ObjectMapper();
        ArrayList<Model> metricsResponse = objectMapper.convertValue(object, new TypeReference<List<Model>>() {
        });

        if (object == null) {
            onRequestFailure(new SpiceException("Something went wrong"));
            return;
        }
    }

    @Override
    public void onRequestFailure(SpiceException spiceException) {
        Snackbar.make(getWindow().getDecorView().getRootView(), spiceException.getMessage(), Snackbar.LENGTH_SHORT)
                .setAction("Action", null).show();
    }
}