How to connect a Socket server via HTTP proxy

后端 未结 8 1189
爱一瞬间的悲伤
爱一瞬间的悲伤 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.(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.

提交回复
热议问题