Android volley to handle redirect
I fixed it catching the http status 301 or 302, reading redirect url and setting it to request then throwing expection which triggers retry.
Edit: Here are the main keys in volley lib which i modified:
Added method public void
setUrl(final String url)
for classRequest
In class BasicNetwork is added check for redirection after // Handle cache validation,
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
, there I read the redirect url withresponseHeaders.get("location")
, callsetUrl
with request object and throw errorError get's catched and it calls
attemptRetryOnException
You also need to have
RetryPolicy
set for theRequest
(seeDefaultRetryPolicy
for this)
Change Redirect Policy of Volley Framework
I think A HttpStack
implementation for Volley that uses OkHttp as its transport is the best solution
RequestQueue queue = Volley.newRequestQueue(this);
Network network = new BasicNetwork(new OkHttpStack());
RequestQueue queue = new RequestQueue(new DiskBasedCache(new File(getCacheDir(), "volley")), network);
queue.start();
OkHttpStack class:
public class OkHttpStack extends HurlStack {
private final OkHttpClient client;
public OkHttpStack() {
this(new OkHttpClient());
}
public OkHttpStack(OkHttpClient client) {
if (client == null) {
throw new NullPointerException("Client must not be null.");
}
this.client = client;
}
@Override protected HttpURLConnection createConnection(URL url) throws IOException {
return client.open(url);
}
}
Update:
if you are using new version of okhttp stack then use
public class OkHttpStack extends HurlStack {
private final OkUrlFactory mFactory;
public OkHttpStack() {
this(new OkHttpClient());
}
public OkHttpStack(OkHttpClient client) {
if (client == null) {
throw new NullPointerException("Client must not be null.");
}
mFactory = new OkUrlFactory(client);
}
@Override
protected HttpURLConnection createConnection(URL url) throws IOException {
return mFactory.open(url);
}
}
How to enable redirection in Volley NetworkImageView?
Isn't it better to use a gilde to load photos?
Or use Gradle:
repositories {
mavenCentral()
google()
}
dependencies {
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
}
use in activity or anything :
Glide
.with(context)
.load(url)
.centerCrop()
.placeholder(R.drawable.imageload)
.into(myImageView);
Just as easily
Redirect User to a certain activity based on Volley's response code (Android)
So I found a fix which was a tad tedious but simple.
Basically I had to override the deliverError method. In that method the errorCode was present, as a result based on that code I was able to perform the redirection.
Also needed to pass the context in the constructor. Needed to make that change in all request calls.
The reason this worked as per my understanding is that deliverError is called when the worker thread needs is trying to merge back to the main UI Thread. This bifurcation is caused in parseNetworkResponse since it's a heavy process which is why a worker thread is assigned to it.
Updated Class:
public class JSONObjectRequestUTF8 extends JsonObjectRequest {
//This is a new parameter
private Context context;
public JSONObjectRequestUTF8(int method, String url, JSONObject jsonRequest,
Listener<JSONObject> listener, ErrorListener errorListener,Context context) {
super(method, url, jsonRequest, listener,
errorListener);
this.context = context;
setShouldCache(false);
}
@Override
protected Response<JSONObject> parseNetworkResponse (NetworkResponse response) {
try {
String utf8String = new String(response.data, "UTF-8");
return Response.success(new JSONObject(utf8String), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
// log error
return Response.error(new ParseError(e));
} catch (JSONException e) {
// log error
return Response.error(new ParseError(e));
}
}
@Override
public void deliverError(VolleyError error) {
if(error.networkResponse.statusCode == HttpURLConnection.HTTP_PRECON_FAILED || error.networkResponse.statusCode == HttpURLConnection.HTTP_UNAUTHORIZED){
Intent i = new Intent(context, LoginActivity.class);
i.putExtra(EReceiptsConstants.ERROR_MESSAGE, EReceiptsConstants.SESSION_MESSAGE);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(i);
return;
}
}
Related Topics
Kotlin Error:Could Not Find Org.Jetbrains.Kotlin:Kotlin-Stdlib-Jre7:1.0.7
Android Listview Row Delete Animation
How Could I Filter the Listview Using Baseadapter
Android Devices with Different Height Takes Same Layout Folder
Why the View Keeps Flashing When Using Jetpack Navigation with Compose
How to Use the Android Volley API
Android Imageview Adjusting Parent's Height and Fitting Width
Android: Application-Wide Font-Size Preference
How to Check If Facebook Is Installed Android
Erase Bitmap Parts Using Porterduff Mode
Gradle Sync Failed Could Not Find Constraint-Layout:1.0.0-Alpha2
Suppress/Block Broadcastreceiver in Another App
Firebase Onmessagereceived Not Called When App Is in the Background
Get the Touch Position Inside the Imageview in Android