15

I am getting "java.lang.ClassCastException" while trying to connect to a url using javax.net.ssl.HttpsURLConnection .

I am using Weblogic Server 10.3.4.

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;



import java.security.cert.X509Certificate;


import java.io.BufferedReader;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author kmrgtm
 *
 */
public class GatewayConnect {


public void ConnectURL()
{
    try
    {

        System.out.println("***** Inside Class File *****");
    // Create a trust manager that does not validate certificate chains
    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) {
            }
        }
    };

    // Install the all-trusting trust manager
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    String urlstr="https://www.google.co.in";

    URL url = new URL(urlstr);

    HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();

    conn  = (HttpsURLConnection)url.openConnection();


        if (conn instanceof javax.net.ssl.HttpsURLConnection) {
        System.out.println("*** openConnection returns an instanceof javax.net.ssl.HttpsURLConnection");
        }
        if (conn instanceof HttpURLConnection) {
        System.out.println("*** openConnection returns an instnace of HttpURLConnection");
        }
    conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
    BufferedReader reader = null;
    reader = new BufferedReader(new InputStreamReader( conn.getInputStream()));
    for (String line; (line = reader.readLine()) != null;) {
        System.out.println("##### line iz :::"+line);
    }




}

catch(Exception e)
{
    e.printStackTrace();
}
}



}

The exception which i am getting is :

**java.lang.ClassCastException: weblogic.net.http.SOAPHttpsURLConnection cannot be cast to javax.net.ssl.HttpsURLConnection
Inside the MessageSendingAction
***** Inside Class File *****
    at com.secureConnect.GatewayConnect.ConnectURL(GatewayConnect.java:68)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.sun.el.parser.AstValue.invoke(Unknown Source)
    at com.sun.el.MethodExpressionImpl.invoke(Unknown Source)
    at javax.faces.component._MethodExpressionToMethodBinding.invoke(_MethodExpressionToMethodBinding.java:78)
    at org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:57)
    at javax.faces.component.UICommand.broadcast(UICommand.java:127)
    at org.ajax4jsf.component.AjaxViewRoot.processEvents(AjaxViewRoot.java:329)
    at org.ajax4jsf.component.AjaxViewRoot.broadcastEventsForPhase(AjaxViewRoot.java:304)
    at org.ajax4jsf.component.AjaxViewRoot.processPhase(AjaxViewRoot.java:261)
    at org.ajax4jsf.component.AjaxViewRoot.processApplication(AjaxViewRoot.java:474)
    at org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:32)
    at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:103)
    at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:76)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:183)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:300)
    at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
    at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:206)
    at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
    at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:388)
    at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:515)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3715)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3681)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2277)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2183)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1454)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:207)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:176)**

Any possible reason of getting this error ?

5
  • There's not much point in putting your 'instanceof' tests after the cast, and there no point whatsoever in casting to a class that you don't even use. Just use it as a URLConnection. Commented Aug 29, 2013 at 13:19
  • 'instanceof' was used for test purpose only. Casting error is coming at this line :: HttpsURLConnection conn = (HttpsURLConnection)url.openConnection(); Commented Aug 29, 2013 at 14:20
  • Code is running fine..here is the output sebsauvage.net/paste/… Commented Aug 29, 2013 at 18:36
  • instanceof was used for test purposes in the wrong place, after the code that threw ClassCastException. That's my point. And my other point is that you don't need the cast. What happened when you tried it? Commented Aug 30, 2013 at 0:51
  • I am using Ecclipse and weblogic 10.3.4 server. If i am running it as a Java Application everything is running Fine. But IF i am tring to run it "Run on Server" , Then only it is throwing the exception "weblogic.net.http.SOAPHttpsURLConnection cannot be cast to javax.net.ssl.HttpsURLConnection". Commented Aug 30, 2013 at 6:52

5 Answers 5

37

I got the solution finally. If we are using Weblogic server, we must define:

set JAVA_OPTIONS=%JAVA_OPTIONS% -DUseSunHttpHandler=true

...in the class path inside the Server Domain.

This will tell the weblogic server to use the Sun Http Handlers and not install its own.

Sign up to request clarification or add additional context in comments.

7 Comments

Hi! I had the same problem, but I don't know where exactly put these instructions... Through the Admin console, in the Server start tab maybe?
You Need to set this in setDomainEnv file inside the bin folder.
Can you post the full path and full file name?
Great, thanks, that worked for me also. @Accollativo you can find out full path path of your server domain when you start/stop the server and check your console. In my case the path is: C:\Users\milko\AppData\Roaming\JDeveloper\system12.1.2.0.40.66.68\DefaultDomain\bin\startWebLogic.cmd just search for JAVA_OPTIONS and add the required parameter
This solution is a workaround, because sometimes you're not allowed to do that on a server installation.
|
28

You also may explicitly define protocol handler. Just create URL using another constructor.

URL url = new URL(null, urlstr, new sun.net.www.protocol.http.Handler());

or

URL url = new URL(null, urlstr, new sun.net.www.protocol.https.Handler());

And it will make the code independent from -DUseSunHttpHandler option.

3 Comments

This is the actual good answer. It should be solved programmatically, because sometimes you are not able (allowed) to change Weblogic's settings.
Thanks, this was helpful actually, no need change to server config.
This is a good answer: no dependency on web container. The problem is that sun.net.www.protocol.https.Handler is a proprietary API, and it may be removed from JDK.
4

Begin from 12.2.1.3.0 you can to enable the new compatible HTTPS connection implementation class by using a new Java system property -DUseJSSECompatibleHttpsHandler=true to get a HttpsURLConnection instance extending javax.net.ssl.HttpsURLConnection.

weblogic.net.http.CompatibleSOAPHttpsURLConnection (extending 
javax.net.ssl.HttpsURLConnection) is returned instead of 
weblogic.net.http.SOAPHttpsURLConnection (not extending 
javax.net.ssl.HttpsURLConnection) that can avoid the ClassCastException 

Please note that when both -DUseSunHttpHandler=true and -DUseJSSECompatibleHttpsHandler=true are specified, -DUseSunHttpHandler will take precedence over -DUseJSSECompatibleHttpsHandler.

1 Comment

Thank you for your comment. This option also works. Do you know if using this option will still make it possible to use the default Weblogic HttpHandler for other applications running on the same Weblogic cluster?
2

More detail on @KmrGtm solution:

Only thing to do is updating WebLogic domain settings in the setDomainEnv script file.

The relevant settings are in the setDomainEnv script file (setDomainEnv.cmd for Windows and setDomainEnv.sh for Linux).

The file is located in the bin subdirectory of the domain directory (/user_projects/domains//bin/) where:

  • is the directory where you installed WebLogic.
  • is the name of the domain where you are installing Studio.

In the file add the JAVA_OPTIONS argument close to the top of the file:

  • For setDomainEnv.cmd (Windows):

set JAVA_OPTIONS=%JAVA_OPTIONS% -DUseSunHttpHandler=true

  • For setDomainEnv.sh (Linux):

JAVA_OPTIONS="%JAVA_OPTIONS% -DUseSunHttpHandler=true"

export JAVA_OPTIONS

Comments

0

java.lang.ClassCastException: weblogic.net.http.SOAPHttpsURLConnection cannot be cast to javax.net.ssl.HttpsURLConnection (Doc ID 2332805.1)

According to the Oracle document above, the parameter

-DUseJSSECompatibleHttpsHandler=true should be used.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.