How to connect a Socket server via HTTP proxy

后端 未结 8 1147
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-02 14:08

I have a piece of code to connect to a Socket server, and it works fine.

Socket socket = new Socket();
socket.connect(new InetSocketAddress(address, port));
         


        
8条回答
  •  囚心锁ツ
    2021-02-02 14:23

    This is from the link I posted previously:

    SocketAddress addr = new InetSocketAddress("webcache.mydomain.com", 8080);
    Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
    

    Remember, this new proxy object represents a proxy definition, nothing more. How do we use such an object? A new openConnection() method has been added to the URL class and takes a Proxy as an argument, it works the same way as openConnection() with no arguments, except it forces the connection to be established through the specified proxy, ignoring all other settings, including the system properties mentioned above.

    So completing the previous example, we can now add:

    URL url = new URL("http://java.sun.com/");
    URLConnection conn = url.openConnection(proxy);
    

    This is from the link I posted earlier. I'm on the iPad so can't format it properly.

    Can you do it this way? I see you're doing sockets directly but you're doing http so maybe do things this way?

提交回复
热议问题