有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法通过代理连接到websocket

我正在尝试使用Java的okhttp3库通过自己的http代理连接到websocket

我已经在EC2实例上设置了代理,并正确配置了安全组。我可以确认它是否有效:

time curl -s --proxy http://X.X.X.X:8888 https://api.binance.com/api/v3/ping

real    0m0.597s
user    0m0.040s
sys     0m0.008s

但是,我试图通过代理连接到websocket的尝试失败。下面是代码

OkHttpClient client = new OkHttpClient.Builder()
        .proxy(new Proxy(Type.HTTP, new InetSocketAddress("X.X.X.X", 8888)))
        .build();

Request request = new Request.Builder()
        .url("wss://fstream.binance.com/stream")
        .build();

WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() {
    @Override
    public void onFailure(final WebSocket webSocket, final Throwable t, final Response response) {
        t.printStackTrace();
    }   
}); 

如果我删除了.proxy(new Proxy(Type.HTTP, new InetSocketAddress("X.X.X.X", 8888)))行,那么它工作得非常好,但是如果我有那一行,我会得到一个异常:

java.io.IOException: Unexpected response code for CONNECT: 403
    at okhttp3.internal.connection.RealConnection.createTunnel(RealConnection.kt:447)
    at okhttp3.internal.connection.RealConnection.connectTunnel(RealConnection.kt:235)
    at okhttp3.internal.connection.RealConnection.connect(RealConnection.kt:170)
    at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:236)
...
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:112)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:87)
    at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.kt:184)
    at okhttp3.RealCall$AsyncCall.run(RealCall.kt:136)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)

我不知道该怎么办?我可以通过终端访问代理,但无法通过它连接到websocket


共 (1) 个答案

  1. # 1 楼答案

    解决了。我的tinyproxy配置文件不允许使用我的IP地址