Reputation: 2006
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?
Upvotes: 21
Views: 31326
Reputation: 5201
url.openConnection() returns HttpURLConnection if your url is an HTTP request, it returns HttpsURLConnection if your url is an HTTPS request.
you can cast HttpsURLConnection to HttpURLConnection, but the inverse can lead to an exception if your url is an HTTP url, which you have seen.
so, to use HttpsURLConnection, you should always cast your url.openConnection() to HttpURLConnection, if you have tasks with HttpsURLConnection, example use your own X509TrustManager, you should check first if your URL is an HTTPS.
herein a sample code:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (url.get_protocol().equals("https")) {
HttpsURLConnection sconn = (HttpsURLConnection)conn;
/* do tasks with https connection */
}
Upvotes: 0
Reputation: 3771
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
Upvotes: 88
Reputation: 3355
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.
Upvotes: 1
Reputation: 281
Simple remove urlConnection.setDoOutput(true);
it will work fine.
Upvotes: 0
Reputation: 15498
url.openConnection();
seems to be returning an object of type libcore.net.http.HttpURLConnectionImpl
while you have declared your "conn" object as being of type import javax.net.ssl.HttpsURLConnection;
. You need to sort up your imports and used objects. Maybe you missed something in the tutorial you were following.
Upvotes: 0