Eclipse Outbound connection blocked : The same url works from web browser

前端 未结 2 714
栀梦
栀梦 2021-01-23 15:35

I am using the HttpURLConnection class to connect to external web service from eclipse, then I am getting a error message \"Connection Refused\"

public class Tes         


        
相关标签:
2条回答
  • 2021-01-23 16:13

    By default, the HttpURLConnection class will not allow localhost as the hostname. You need to define a custom hostname verifier which will allow localhost. You can place this code into a static block at the top of the class where you intend to use HttpURLConnection:

    public final class YourClassName {
        static {
            //for localhost testing only
            javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
                new javax.net.ssl.HostnameVerifier(){
    
                        public boolean verify(String hostname,
                                          javax.net.ssl.SSLSession sslSession) {
                            if (hostname.equals("localhost")) {
                                return true;
                            }
                            return false;
                        }
                    });
        }
    
        // use HttpURLConnection here ...
    }
    
    0 讨论(0)
  • 2021-01-23 16:15

    Please find the working code,

    PROXY_SERVER set to a valid proxy server and port for http I am using is 8080

    proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_SERVER, PROXY_PORT));

    And when you establish the connection pass the proxy as an argument.

    urlConnection = (HttpURLConnection) ((new URL(URI).openConnection(proxy)));

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