Skip to content

Instantly share code, notes, and snippets.

@paour
Created September 16, 2016 15:22
Show Gist options
  • Save paour/bf58afa8969640e36e9bd87f85a6c5df to your computer and use it in GitHub Desktop.
Save paour/bf58afa8969640e36e9bd87f85a6c5df to your computer and use it in GitHub Desktop.
class ReverseProxyDispatcher extends Dispatcher {
private final OkHttpClient client;
private final HttpUrl serverUrl;
public ReverseProxyDispatcher(HttpUrl url) {
serverUrl = url;
client = new OkHttpClient.Builder().build();
}
@Override
public MockResponse dispatch(final RecordedRequest request) throws InterruptedException {
HttpUrl proxiedUri = HttpUrl.parse("http://example.com" + request.getPath())
.newBuilder()
.scheme(serverUrl.scheme())
.host(serverUrl.host())
.build();
Request.Builder requestBuilder = new Request.Builder()
.url(proxiedUri)
.headers(request.getHeaders());
if (request.getBodySize() != 0) {
requestBuilder.method(request.getMethod(), new RequestBody() {
@Override
public MediaType contentType() {
return MediaType.parse(request.getHeader("Content-Type"));
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
request.getBody().readAll(sink);
}
});
}
Response response = null;
try {
response = client.newCall(requestBuilder.build()).execute();
} catch (IOException e) {
response = null;
}
if (response == null) {
return new MockResponse()
.setStatus("Reverse proxy error")
.setResponseCode(500);
}
return new MockResponse()
.setHeaders(response.headers())
.setBody(response.body().source().buffer())
.setResponseCode(response.code());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment