java - 无法通过代理连接到 websocket

标签 java http websocket proxy okhttp

我正在尝试使用 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))) ,那么它工作得很好,但如果我有那行,我得到了异常(exception):

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。

最佳答案

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

关于java - 无法通过代理连接到 websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60247425/

相关文章:

java - java中如何避免空指针异常

java - 在java中访问文件/文件夹

java - 如果我们将 SessionScoped bean 注入(inject)到 Stateless bean 中,如果没有 HTTP session 会发生什么?

PHP Curl 和 HttpRequest 的区别

r - R 中的 Websocket

http - Websocket、Server Sent Events (SSE) 和 HTTP2 的 Server Pushing 有什么区别?

java - 为什么映射节点得到 java.lang.RuntimeException?

javascript - 使用Express服务器来控制nodejs应用程序

php - 非浏览器发送的 HTTP 请求和 PHP session

scala - tomcat 网络套接字 : cannot connect to tomcat server