Search code examples
javawebhttpsurlconnection

Java HttpURLConnection command works perfectly through command line but not through web UI


I have a java file to execute an HttpURLConnection command, which when I execute through command line, works perfectly to fetch data from the URL.
I have mapped a URL to this activity in my web application and when I invoke this activity through the web UI this code works fine except the HttpURLConnection command now returns empty results.

public static String getData()
 {  
    String str = "";
    try{
    TrustManager[] trustAllCerts = new TrustManager[] 
    {
       new X509TrustManager()
        {
          public java.security.cert.X509Certificate[] getAcceptedIssuers() 
          {
            return null;
          }
          public void checkClientTrusted(X509Certificate[] certs, String authType) {  }
          public void checkServerTrusted(X509Certificate[] certs, String authType) {  }
        }
     };
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
         HostnameVerifier allHostsValid = new HostnameVerifier()
         {
            public boolean verify(String hostname, SSLSession session) 
             {
                           return true;
             }
         };
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    URL url = new URL("My URL");
    URLConnection con = url.openConnection();
    Reader reader = new InputStreamReader(con.getInputStream());                
    while (true) 
    {
       int ch = reader.read();
       if (ch==-1) {
           break;
       }
       str += (char)ch;                                                                  
    }   }catch(Exception e){}
    return str;

I can't understand what is causing this behavior please help me fix this.


Solution

  • This reason for this is web browsers have a security in place to protected websites from unwanted queries. This is the CORS policy.
    If a domain does not want incoming requests from outside world this policy provides this security. It is upto the domain to turn this policy off. So as a client, you really can't do anything.