-
-
Save CMingTseng/060cf15d69d43436097fb7cf6b0f89ce to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.io.PrintStream; | |
import okhttp3.Headers; | |
import okhttp3.OkHttpClient; | |
import okhttp3.Request; | |
import okhttp3.Response; | |
import okhttp3.mockwebserver.Dispatcher; | |
import okhttp3.mockwebserver.MockResponse; | |
import okhttp3.mockwebserver.MockWebServer; | |
import okhttp3.mockwebserver.RecordedRequest; | |
import okio.Buffer; | |
public final class MockWebServerProxy { | |
private final OkHttpClient client = new OkHttpClient(); | |
public void run() throws Exception { | |
MockWebServer proxy = new MockWebServer(); | |
proxy.setDispatcher(new Dispatcher() { | |
@Override public MockResponse dispatch(RecordedRequest proxyRequest) { | |
try { | |
Request request = new Request.Builder() | |
.url(proxyRequest.getRequestUrl() | |
.newBuilder() | |
.scheme("https") | |
.host("square.com") | |
.port(443) | |
.build()) | |
.headers(proxyRequest.getHeaders()).build(); | |
Response response = client.newCall(request).execute(); | |
MockResponse proxyResponse = new MockResponse(); | |
proxyResponse.setHeaders(response.headers()); | |
proxyResponse.setResponseCode(response.code()); | |
Buffer responseBody = new Buffer(); | |
responseBody.writeAll(response.body().source()); | |
proxyResponse.setBody(responseBody); | |
return proxyResponse; | |
} catch (IOException e) { | |
Buffer responseBody = new Buffer(); | |
e.printStackTrace(new PrintStream(responseBody.outputStream())); | |
MockResponse proxyResponse = new MockResponse(); | |
proxyResponse.setResponseCode(500); | |
proxyResponse.setBody(responseBody); | |
return proxyResponse; | |
} | |
} | |
}); | |
Request request = new Request.Builder() | |
.url(proxy.url("/robots.txt")) | |
.build(); | |
try (Response response = client.newCall(request).execute()) { | |
//if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); | |
Headers responseHeaders = response.headers(); | |
for (int i = 0; i < responseHeaders.size(); i++) { | |
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); | |
} | |
System.out.println(response.body().string()); | |
} | |
} | |
public static void main(String... args) throws Exception { | |
new MockWebServerProxy().run(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment