If you’ve ever tried to upload a file over HTTPS in an Android app using HttpURLConnection, you might have encountered the frustrating error:

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

This error occurs when your code attempts to cast an HttpURLConnection instance to HttpsURLConnection, but the underlying connection is actually an HTTP (not HTTPS) implementation. While the error message seems cryptic at first, it’s rooted in a few common mistakes—most of which are easy to fix with careful debugging.

In this blog, we’ll break down the root causes of this exception, walk through step-by-step solutions, and share best practices to prevent it from happening again. Whether you’re a beginner or an experienced Android developer, this guide will help you resolve the issue and ensure smooth HTTPS file uploads.

Discover more

Spring

RESTful

Spring Frameworks

Table of Contents#

  1. Understanding the Error
  2. Root Causes of the Exception
  3. Step-by-Step Solutions
  4. Advanced Scenarios & Alternatives
  5. Prevention Tips
  6. Conclusion
  7. References

Understanding the Error#

Before diving into fixes, let’s clarify what’s happening under the hood:

  • HttpURLConnection: The base class for handling HTTP connections in Android. It supports HTTP/1.1 and is used for standard HTTP requests.
  • HttpsURLConnection: A subclass of HttpURLConnection specifically designed for HTTPS (HTTP over TLS/SSL) connections. It adds methods for configuring SSL/TLS settings (e.g., certificate validation).

The error ClassCastException occurs when you try to cast an object of type HttpURLConnectionImpl (Android’s concrete implementation of HttpURLConnection for HTTP) to HttpsURLConnection. This is like trying to cast a "Car" to a "SportsCar"—it only works if the car is a sports car. Similarly, the cast only works if the connection is actually an HTTPS connection.

Root Causes of the Exception#

Let’s explore the most common reasons this error occurs:

1. Using an HTTP URL Instead of HTTPS#

The #1 culprit! If your URL starts with http:// (not https://), URL.openConnection() returns an HttpURLConnection (not HttpsURLConnection). Casting this to HttpsURLConnection will fail immediately.

Example:

// ❌ URL uses HTTP protocolURL url = new URL("http://your-server.com/upload"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); // ERROR!

2. Forcing a Cast Without Checking the Protocol#

Even if you think your URL uses HTTPS, hardcoding the cast without validating the protocol is risky. For example:

  • Typos in the URL (e.g., htts:// instead of https://).
  • Dynamic URLs (e.g., user-provided or fetched from a server) that accidentally use HTTP.

3. Server Redirects from HTTPS to HTTP#

By default, HttpsURLConnection follows HTTP redirects (status codes 3xx). If the server redirects an HTTPS request to an HTTP URL, the connection type changes from HttpsURLConnection to HttpURLConnection, causing the cast to fail.

4. Incorrect Handling of Custom URL Stream Handlers#

Rarely, custom URLStreamHandler implementations (used to handle non-standard protocols) might return HttpURLConnection even for HTTPS URLs, breaking the cast.

Step-by-Step Solutions#

Let’s fix the error by addressing each root cause with actionable steps.

Solution 1: Verify the URL Protocol#

First, ensure your URL uses https://.

Step 1.1: Check the URL String#

Double-check the URL for typos. Ensure it starts with https:// (lowercase; protocols are case-insensitive, but url.getProtocol() returns lowercase).

Step 1.2: Validate the Protocol Programmatically#

Before casting, confirm the URL’s protocol is HTTPS using URL.getProtocol().

Example:

URL url = new URL("https://your-server.com/upload");  // Validate protocol before castingif ("https".equals(url.getProtocol())) {     HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();     // Proceed with HTTPS-specific logic (e.g., SSL settings)} else {    throw new IllegalArgumentException("URL must use HTTPS protocol"); }

Solution 2: Avoid Forced Casts – Use instanceof#

Even with a valid HTTPS URL, use instanceof to check the connection type before casting. This adds a safety net for edge cases (e.g., redirects or custom handlers).

Example:

URL url = new URL("https://your-server.com/upload"); URLConnection connection = url.openConnection();  if (connection instanceof HttpsURLConnection) {     // Safe cast to HttpsURLConnection    HttpsURLConnection httpsConn = (HttpsURLConnection) connection;     // Configure HTTPS settings (e.g., setSSLSocketFactory)} else {    // Handle non-HTTPS connection (e.g., log error, abort upload)    Log.e("UploadError", "Connection is not HTTPS: " + connection.getClass().getName());}

Solution 3: Handle Redirects Explicitly#

To prevent redirects from switching protocols, disable automatic redirect following and handle them manually.

Step 3.1: Disable Automatic Redirects#
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setInstanceFollowRedirects(false); // Disable auto-redirects
Step 3.2: Manually Handle Redirects#

Check for redirect status codes (301, 302, etc.) and validate the new URL’s protocol:

int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {     String redirectUrl = conn.getHeaderField("Location");     URL newUrl = new URL(redirectUrl);      // Ensure redirect URL uses HTTPS    if (!"https".equals(newUrl.getProtocol())) {         throw new SecurityException("Redirect to non-HTTPS URL is not allowed");     }     // Retry with the new HTTPS URL    HttpsURLConnection newConn = (HttpsURLConnection) newUrl.openConnection(); }

Solution 4: Fix Custom URL Stream Handlers#

If using a custom URLStreamHandler, ensure it returns HttpsURLConnection for HTTPS URLs. Refer to the Android URLStreamHandler docs for guidance.

Advanced Scenarios & Alternatives#

If you’re still stuck, consider these advanced approaches:

Use OkHttp Instead of HttpURLConnection#

HttpURLConnection is error-prone for complex scenarios. OkHttp (a modern HTTP client) simplifies HTTPS handling and avoids casting issues entirely.

Example OkHttp File Upload:

OkHttpClient client = new OkHttpClient();  RequestBody requestBody = new MultipartBody.Builder()    .setType(MultipartBody.FORM)    .addFormDataPart("file", "filename.jpg",         RequestBody.create(MediaType.parse("image/jpeg"), new File("path/to/file.jpg")))    .build(); Request request = new Request.Builder()    .url("https://your-server.com/upload") // HTTPS enforced    .post(requestBody)    .build(); try (Response response = client.newCall(request).execute()) {    if (!response.isSuccessful()) throw new IOException("Upload failed: " + response);    Log.d("UploadSuccess", response.body().string());}

OkHttp automatically handles HTTPS, redirects, and SSL configuration, making it far less error-prone than raw HttpsURLConnection.

Android 9+ (API 28) Cleartext Traffic Restrictions#

Android 9 (API 28) blocks cleartext (HTTP) traffic by default. If your app targets API 28+, trying to use HTTP will fail silently or force you to use android:usesCleartextTraffic="true" in AndroidManifest.xml, which is insecure. This often leads developers to accidentally use HTTP URLs, triggering the ClassCastException.

Fix: Always use HTTPS URLs. If you must use HTTP (e.g., for testing), add a network security config to allow cleartext traffic for specific domains (not recommended for production).

Prevention Tips#

To avoid this error in the future:

  1. Enforce HTTPS Everywhere: Use https:// for all server communication. Never hardcode HTTP URLs.
  2. Validate URLs Dynamically: For user-provided or server-fetched URLs, check getProtocol() before use.
  3. Avoid Raw HttpURLConnection: Use modern libraries like OkHttp or Retrofit (built on OkHttp) for robust HTTP/HTTPS handling.
  4. Test Redirects: Simulate server redirects in testing to ensure your app handles protocol changes gracefully.
  5. Enable Lint Checks: Use Android Lint to flag hardcoded HTTP URLs (add tools:ignore="HttpURLConnection" only if absolutely necessary).

Discover more

Spring Security

Application software

Authentication

Conclusion#

The ClassCastException between HttpURLConnectionImpl and HttpsURLConnection is almost always caused by incorrect URL protocols or unsafe casting. By:

  • Verifying URLs use https://,
  • Checking the protocol before casting,
  • Handling redirects explicitly,
  • And using modern libraries like OkHttp,

you can resolve this error and ensure secure, reliable HTTPS file uploads in your Android app.

Discover more

Application programming interface

application

applications

References#

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐