How to connect a Socket server via HTTP proxy

后端 未结 8 1162
爱一瞬间的悲伤
爱一瞬间的悲伤 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:46

    Well, you can manage the proxy by setting the requested url right after the proxy's url, or using Java URL as following:

    URL u = new URL("http", ProxyHost, ProxyPort, destinationAddress);
    

    By using this you build an URL like http://ProxyHost:ProxyPorthttp://destinationAddress so you don't have to set a Proxy class instance in Java that will likely throw the mentioned exception:

    java.lang.IllegalArgumentException: Proxy is null or invalid type
        at java.net.Socket.<init>(Socket.java:88)
    

    If you need to manage authentication settings you can always set the authenticator as default.

    final String authUser = myAuthUser;
            final String authPassword = myAuthPassword;
            Authenticator.setDefault(
               new Authenticator() {
                  public PasswordAuthentication getPasswordAuthentication() {
                     return new PasswordAuthentication(
                           authUser, authPassword.toCharArray());
                  }
               }
            );
    

    Even though it's a very "rudimental" way to set a proxy it's very likely to work for HTTP Type Proxies if that's the kind of proxy you have to set.

    0 讨论(0)
  • 2021-02-02 14:46

    As per Wikipedia on HTTP tunneling, the important thing about a HTTP proxy is that it proxies the HTTP protocol.

    So if you have a server and a client and wish them to communicate through a HTTP proxy then both the server and client must be modified to communicate the HTTP protocol.

    Alternatively you need additional software that can implement a VPN over HTTP, such as OpenVPN.

    Edit: An exception is that some HTTP proxy servers support and have enabled a method called HTTP CONNECT which after a basic setup process over HTTP permits the creation and routing of a regular TCP socket. This permits connectivity to applications without the hard work of full conversion to HTTP tunneling. A good example of this is MSN Messenger. However as the Wikipedia articles notes this feature is often disabled, or not even supported for security reasons.

    0 讨论(0)
提交回复
热议问题