Skip to content

Instantly share code, notes, and snippets.

@sdsantos
Created March 3, 2017 22:59
Show Gist options
  • Save sdsantos/c838d4e0af9e942abb5397ca157cc49d to your computer and use it in GitHub Desktop.
Save sdsantos/c838d4e0af9e942abb5397ca157cc49d to your computer and use it in GitHub Desktop.
public class MockApiInterceptor implements Interceptor {
@Override
public Response intercept(Interceptor.Chain chain) {
Request request = chain.request();
MockResponse mockResponse = getResponse(request);
return new Response.Builder().request(request)
.code(mockResponse.code)
.protocol(Protocol.HTTP_2)
.body(ResponseBody.create(MediaType.parse("text/json"), mockResponse.body))
.build();
}
private MockResponse getResponse(Request request) {
String requestUrl = request.url().encodedPath();
if (requestUrl.endsWith("/login")) {
// TODO
} else {
return new MockResponse("{}");
}
}
private String loadJson(String fileName) {
try {
InputStream is = getClass().getClassLoader().getResourceAsStream("responses/" + fileName + ".json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer, "UTF-8");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private static class MockResponse {
int code;
String body;
private MockResponse(String body) {
this(HttpURLConnection.HTTP_OK, body);
}
private MockResponse(int code, String body) {
this.code = code;
this.body = body;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment