Skip to content

Instantly share code, notes, and snippets.

@mbunyard
Created November 18, 2016 21:11
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save mbunyard/78311b25aaba8b9bfec380f66c868644 to your computer and use it in GitHub Desktop.
Save mbunyard/78311b25aaba8b9bfec380f66c868644 to your computer and use it in GitHub Desktop.
OkHttp3 interceptor which provides a mock response from local resource file.
package com.rogerthat.network.util;
import android.content.Context;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* OkHttp3 interceptor which provides a mock response from local resource file.
*/
public class MockResponseInterceptor implements Interceptor {
private static final int BUFFER_SIZE = 1024 * 4;
private Context context;
private String scenario;
public MockResponseInterceptor(Context context, String scenario) {
this.context = context.getApplicationContext();
this.scenario = scenario;
}
public MockResponseInterceptor(Context context) {
this.context = context.getApplicationContext();
}
public void setScenario(String scenario) {
this.scenario = scenario;
}
@Override
public Response intercept(Chain chain) throws IOException {
// Get resource ID for mock response file.
String fileName = getFilename(chain.request(), scenario);
int resourceId = getResourceId(fileName);
if (resourceId == 0) {
// Attempt to fallback to default mock response file.
fileName = getFilename(chain.request(), null);
resourceId = getResourceId(fileName);
if (resourceId == 0) {
throw new IOException("Could not find res/raw/" + fileName);
}
}
// Get input stream and mime type for mock response file.
InputStream inputStream = context.getResources().openRawResource(resourceId);
String mimeType = URLConnection.guessContentTypeFromStream(inputStream);
if (mimeType == null) {
mimeType = "application/json";
}
// Build and return mock response.
return new Response.Builder()
.addHeader("content-type", mimeType)
.body(ResponseBody.create(MediaType.parse(mimeType), toByteArray(inputStream)))
.code(200)
.message("Mock response from res/raw/" + fileName)
.protocol(Protocol.HTTP_1_0)
.request(chain.request())
.build();
}
private String getFilename(Request request, String scenario) throws IOException {
String requestedMethod = request.method();
String prefix = scenario == null ? "" : scenario + "_";
String filename = prefix + requestedMethod + request.url().url().getPath();
filename = filename.replace("/", "_").replace("-", "_").toLowerCase();
return filename;
}
private int getResourceId(String filename) {
return context.getResources().getIdentifier(filename, "raw", context.getPackageName());
}
private static byte[] toByteArray(InputStream is) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
byte[] b = new byte[BUFFER_SIZE];
int n = 0;
while ((n = is.read(b)) != -1) {
output.write(b, 0, n);
}
return output.toByteArray();
} finally {
output.close();
}
}
}
@Wolf00Bomber
Copy link

What would i do with this??
Can you give me a complete implementation for working with this?

@joaocsousa
Copy link

joaocsousa commented Feb 17, 2017

👍 Thanks for this. Saved me a bit of work there. @Wolf00Bomber to use this, just add an instance of this interceptor to the list of interceptors when you build the okhttpclient, like so

OkHttpClient.Builder builder = new OkHttpClient.Builder();
...
builder.addInterceptor(new MockResponseInterceptor(application));

It should probably be the first interceptor you add, if your other interceptors require valid data (like hmac verification, etc).

@silentsudo
Copy link

Wonderful sir.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment