Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using java class HttpsURLConnection

Tags:

java

https

I have a small piece of code which basically impements a HTTP-Client, i.e. it POSTS request and works with re RESPONSE. As long as HTTP is concenerned everthing work well. For some reason I now have to support HTTPS too. So here is briefly what I do in order to get a connection opened:

 URL url = new URL(serverAddress);  HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection(); 

This fails, stating:

sun.net.www.protocol.https.HttpsURLConnectionImpl cannot be cast to com.sun.net.ssl.HttpsURLConnection 

I guess this is kinda trivial, but I just don't get what I'm doing wrong in this one... Googled it, and the code just looks right - not?

any ideas are appreciated!

like image 653
KB22 Avatar asked Jun 14 '10 14:06

KB22


People also ask

What is HttpsURLConnection in Java?

HttpURLConnection class is an abstract class directly extending from URLConnection class. It includes all the functionality of its parent class with additional HTTP-specific features. HttpsURLConnection is another class that is used for the more secured HTTPS protocol.

When should I use HttpURLConnection?

The method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance. It sets whether HTTP redirects (requests with response code) should be automatically followed by HttpURLConnection class.

Can HttpURLConnection be used with https?

HttpsURLConnection extends HttpURLConnection with support for https-specific features. A URLConnection with support for HTTP-specific features.


2 Answers

Just keep it java.net.URLConnection or cast it to java.net.HttpURLConnection instead. Both offers methods to do the desired task as good.


A side remark unrelated to the technical problem: you should never explicitly import/use Sun Java SE implementation specific classes in your code. Those are undocumented classes and are subject to changes which may cause your code break when you upgrade the JVM. On the other hand, your code may also break when you run it at a different brand JVM.


Update: since you seem to accidentally have imported it, go to Window > Preferences > Java > Appearance > Type Filters and Add com.sun.* and sun.* to the list. This way you won't ever import them accidentally:

enter image description here

like image 95
BalusC Avatar answered Oct 02 '22 16:10

BalusC


Your url's protocol should also be https and not http. Check your url.

like image 41
Salman Zafar Avatar answered Oct 02 '22 16:10

Salman Zafar