如何实现模拟Web服务器以使用代理



我正在尝试从Square实现一个MockWebServer,我在代理后面。问题是每次我执行我的检测测试都会失败,因为我对我的 MockWeb Server 执行的每个请求都会得到 407。

debug.level.titleD/OkHttp: <-- 407 Proxy Authentication Required http://localhost:12345/user/login (767ms)

如您所见,我指向我的本地主机,我不知道为什么我会得到这个!

这是我的模拟网络服务器实现!

public class MockedTestServer {

private final int PORT = 12345;
private final MockWebServer server;
private int lastResponseCode;
private String lastRequestPath;
/**
 * Creates and starts a new server, with a non-default dispatcher
 *
 * @throws Exception
 */
public MockedTestServer() throws Exception {
    server = new MockWebServer();
    server.start(PORT);
    setDispatcher();
}
private void setDispatcher() {
    final Dispatcher dispatcher = new Dispatcher() {
        @Override
        public MockResponse dispatch(final RecordedRequest request) throws InterruptedException {
            try {
                final String requestPath = request.getPath();
                final MockResponse response = new MockResponse().setResponseCode(200);
                String filename;

                // response for alerts
                if (requestPath.equals(Constantes.ACTION_LOGIN)) {
                    filename = ConstantesJSON.LOGIN_OK;
                } else {
                    // no response
                    lastResponseCode = 404;
                    return new MockResponse().setResponseCode(404);
                }
                lastResponseCode = 200;
                response.setBody(RestServiceTestHelper.getStringFromFile(filename));
                lastRequestPath = requestPath;
                return response;
            } catch (final Exception e) {
                throw new InterruptedException(e.getMessage());
            }
        }
    };
    server.setDispatcher(dispatcher);
}

public String getLastRequestPath() {
    return lastRequestPath;
}
public String getUrl() {
    return server.url("/").toString();
}
public int getLastResponseCode() {
    return lastResponseCode;
}

public void setDefaultDispatcher() {
    server.setDispatcher(new QueueDispatcher());
}

public void enqueueResponse(final MockResponse response) {
    server.enqueue(response);
}
public void shutdownServer() throws IOException {
    server.shutdown();
}

执行仪器测试时的终点是"/"。

仅当我在代理网络后面时,才会发生此问题,如果我在移动设备中切换到另一个不在代理后面的网络,则模拟服务器运行良好。知道我做错了什么吗?

编辑:当我在代理后面时,调度员永远不会被召唤

好吧,

我最后只是失败了....结果我的okhttp3客户端指向真正的代理服务器,而不是本地主机中的模拟Web服务器。我通过在测试Flavor时向我的okhttp3客户端添加代理,然后将其添加到Retrofit2构建器中来解决此问题。代码如下所示。

if (BuildConfig.TEST_PROXY){
            try {
                InetSocketAddress sock = new InetSocketAddress(InetAddress.getByName("localhost"),12345);
                builderOkhttpClient.proxy(new Proxy(Proxy.Type.HTTP, sock));
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }

请务必注意,构建 InetSocketAddress 时的端口与模拟 Web 服务器端口相同。

最新更新