android volley设置编码,Android设置Volley以从缓存中使用

请注意,如果Web服务支持缓存输出,则无需在CacheRequest下面使用,因为Volley它将自动缓存。

对于您的问题,我在内部使用了一些代码parseCacheHeaders(并引用了@ oleksandr_yefremov的代码)。我测试了以下代码。当然也可以使用JsonArrayRequest。希望对您有所帮助!

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(0, mUrl, new Response.Listener() {

@Override

public void onResponse(JSONObject response) {

try {

mTextView.setText(response.toString(5));

} catch (JSONException e) {

mTextView.setText(e.toString());

}

}

}, new Response.ErrorListener() {

@Override

public void onErrorResponse(VolleyError error) {

}

}) {

@Override

protected Response parseNetworkResponse(NetworkResponse response) {

try {

Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);

if (cacheEntry == null) {

cacheEntry = new Cache.Entry();

}

final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background

final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely

long now = System.currentTimeMillis();

final long softExpire = now + cacheHitButRefreshed;

final long ttl = now + cacheExpired;

cacheEntry.data = response.data;

cacheEntry.softTtl = softExpire;

cacheEntry.ttl = ttl;

String headerValue;

headerValue = response.headers.get("Date");

if (headerValue != null) {

cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);

}

headerValue = response.headers.get("Last-Modified");

if (headerValue != null) {

cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);

}

cacheEntry.responseHeaders = response.headers;

final String jsonString = new String(response.data,

HttpHeaderParser.parseCharset(response.headers));

return Response.success(new JSONObject(jsonString), cacheEntry);

} catch (UnsupportedEncodingException e) {

return Response.error(new ParseError(e));

} catch (JSONException e) {

return Response.error(new ParseError(e));

}

}

@Override

protected void deliverResponse(JSONObject response) {

super.deliverResponse(response);

}

@Override

public void deliverError(VolleyError error) {

super.deliverError(error);

}

@Override

protected VolleyError parseNetworkError(VolleyError volleyError) {

return super.parseNetworkError(volleyError);

}

};

MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);

更新:

如果需要基类,请参考以下代码:

public class CacheRequest extends Request {

private final Response.Listener mListener;

private final Response.ErrorListener mErrorListener;

public CacheRequest(int method, String url, Response.Listener listener, Response.ErrorListener errorListener) {

super(method, url, errorListener);

this.mListener = listener;

this.mErrorListener = errorListener;

}

@Override

protected Response parseNetworkResponse(NetworkResponse response) {

Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);

if (cacheEntry == null) {

cacheEntry = new Cache.Entry();

}

final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background

final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely

long now = System.currentTimeMillis();

final long softExpire = now + cacheHitButRefreshed;

final long ttl = now + cacheExpired;

cacheEntry.data = response.data;

cacheEntry.softTtl = softExpire;

cacheEntry.ttl = ttl;

String headerValue;

headerValue = response.headers.get("Date");

if (headerValue != null) {

cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);

}

headerValue = response.headers.get("Last-Modified");

if (headerValue != null) {

cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);

}

cacheEntry.responseHeaders = response.headers;

return Response.success(response, cacheEntry);

}

@Override

protected void deliverResponse(NetworkResponse response) {

mListener.onResponse(response);

}

@Override

protected VolleyError parseNetworkError(VolleyError volleyError) {

return super.parseNetworkError(volleyError);

}

@Override

public void deliverError(VolleyError error) {

mErrorListener.onErrorResponse(error);

}

}

然后在MainActivity中,您可以像这样调用

CacheRequest cacheRequest = new CacheRequest(0, mUrl, new Response.Listener() {

@Override

public void onResponse(NetworkResponse response) {

try {

final String jsonString = new String(response.data,

HttpHeaderParser.parseCharset(response.headers));

JSONObject jsonObject = new JSONObject(jsonString);

mTextView.setText(jsonObject.toString(5));

} catch (UnsupportedEncodingException | JSONException e) {

e.printStackTrace();

}

}

}, new Response.ErrorListener() {

@Override

public void onErrorResponse(VolleyError error) {

mTextView.setText(error.toString());

}

});

MySingleton.getInstance(this).addToRequestQueue(cacheRequest);

用全源代码更新:

MainActivity.java:

package com.example.cachevolley;

import android.content.Context;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.Menu;

import android.view.MenuItem;

import android.widget.TextView;

import android.widget.Toast;

import com.android.volley.Cache;

import com.android.volley.NetworkResponse;

import com.android.volley.Request;

import com.android.volley.RequestQueue;

import com.android.volley.Response;

import com.android.volley.VolleyError;

import com.android.volley.toolbox.HttpHeaderParser;

import com.android.volley.toolbox.Volley;

import org.json.JSONException;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

public class MainActivity extends AppCompatActivity {

private final Context mContext = this;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

final TextView textView = (TextView) findViewById(R.id.textView);

RequestQueue queue = Volley.newRequestQueue(this);

String url = "http://192.168.0.100/apitest";

CacheRequest cacheRequest = new CacheRequest(0, url, new Response.Listener() {

@Override

public void onResponse(NetworkResponse response) {

try {

final String jsonString = new String(response.data,

HttpHeaderParser.parseCharset(response.headers));

JSONObject jsonObject = new JSONObject(jsonString);

textView.setText(jsonObject.toString(5));

Toast.makeText(mContext, "onResponse:\n\n" + jsonObject.toString(), Toast.LENGTH_SHORT).show();

} catch (UnsupportedEncodingException | JSONException e) {

e.printStackTrace();

}

}

}, new Response.ErrorListener() {

@Override

public void onErrorResponse(VolleyError error) {

Toast.makeText(mContext, "onErrorResponse:\n\n" + error.toString(), Toast.LENGTH_SHORT).show();

}

});

// Add the request to the RequestQueue.

queue.add(cacheRequest);

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.menu_main, menu);

return true;

}

@Override

public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will

// automatically handle clicks on the Home/Up button, so long

// as you specify a parent activity in AndroidManifest.xml.

int id = item.getItemId();

//noinspection SimplifiableIfStatement

if (id == R.id.action_settings) {

return true;

}

return super.onOptionsItemSelected(item);

}

private class CacheRequest extends Request {

private final Response.Listener mListener;

private final Response.ErrorListener mErrorListener;

public CacheRequest(int method, String url, Response.Listener listener, Response.ErrorListener errorListener) {

super(method, url, errorListener);

this.mListener = listener;

this.mErrorListener = errorListener;

}

@Override

protected Response parseNetworkResponse(NetworkResponse response) {

Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);

if (cacheEntry == null) {

cacheEntry = new Cache.Entry();

}

final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background

final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely

long now = System.currentTimeMillis();

final long softExpire = now + cacheHitButRefreshed;

final long ttl = now + cacheExpired;

cacheEntry.data = response.data;

cacheEntry.softTtl = softExpire;

cacheEntry.ttl = ttl;

String headerValue;

headerValue = response.headers.get("Date");

if (headerValue != null) {

cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);

}

headerValue = response.headers.get("Last-Modified");

if (headerValue != null) {

cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);

}

cacheEntry.responseHeaders = response.headers;

return Response.success(response, cacheEntry);

}

@Override

protected void deliverResponse(NetworkResponse response) {

mListener.onResponse(response);

}

@Override

protected VolleyError parseNetworkError(VolleyError volleyError) {

return super.parseNetworkError(volleyError);

}

@Override

public void deliverError(VolleyError error) {

mErrorListener.onErrorResponse(error);

}

}

}

清单文件:

package="com.example.cachevolley" >

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

android:name=".MainActivity"

android:label="@string/app_name" >

布局文件:

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context=".MainActivity">

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/hello_world" />

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值