Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.ClassCastException: libcore.net.http.HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection

I'm writing a bit of code to upload a file from the device to the cloud over HTTPS.

Relevant snippet:

HttpsURLConnection conn = null; 
URL url = new URL(urlstring);
conn = (HttpsURLConnection) url.openConnection(); // exception here.

But the cast won't compile:

06-20 15:58:05.311: E/FNF(30286): java.lang.ClassCastException: libcore.net.http.HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection

I found this similar question: Using java class HttpsURLConnection, but I am not importing anything from the sun package.

My imports:

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import android.net.Uri;
import javax.net.ssl.HttpsURLConnection;
import android.util.Log;
import edu.mit.media.funf.storage.RemoteFileArchive;
import edu.mit.media.funf.util.LogUtil;

I've been scratching my head about this one for a while now, any suggestions?

like image 978
Teddy Avatar asked Jun 20 '12 20:06

Teddy


2 Answers

Method 1: Your urlString must begin with https:// and not http:// for you to be able to cast it to a HttpsURLConnection.

Method 2: if your urlString starts with http://, changing HttpsURLConnection to HttpURLConnection should work

like image 73
cklab Avatar answered Nov 09 '22 10:11

cklab


I had same Exception java.lang.ClassCastException: libcore.net.http.HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection

uri = new URL("http://www.google.com");
HttpsURLConnection connection = (HttpsURLConnection) uri.openConnection(); // Exception

I changed

uri = new URL("http://www.google.com");

to

uri = new URL("https://www.google.com");

Now it is working perfectly.

like image 25
anoopknr Avatar answered Nov 09 '22 11:11

anoopknr