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

Teddy picture Teddy · Jun 20, 2012 · Viewed 24.5k times · Source

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?

Answer

cklab picture cklab · Jun 20, 2012

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