Tony
Tony

Reputation: 3805

How to send HTTPS request from GAE servlet?

I'm trying to send https request using GAE technologies. But if I use

HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

it will crash

java.lang.ClassCastException: com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection cannot be cast to javax.net.ssl.HttpsURLConnection

If I change HttpsURLConnection to HttpURLConnection, everything will work ok, but I don't think https advantages will be used. So how can I send https request properly?

Upvotes: 1

Views: 748

Answers (2)

Surya Nair
Surya Nair

Reputation: 111

HttpURLConnection works for me

Upvotes: 0

AreSo
AreSo

Reputation: 643

I assume, that obj is of java.net.URL type. Simply, you should not use javax.net.ssl.HttpsURLConnection in this case.

URL#openConnection() method returns type java.net.URLConnection, and does not provide almost any guarantees on it subtypes (apart of weird javadoc description, see below*), and Google makes use of it. Your application should not rely on specifics of HttpsURLConnection. There are two options:

  • use only URLConnection - guaranteed by API,
  • use HttpURLConnection as URLFetchServiceStreamHandler$Connection extends it, and it is unlikely to be changed.

In both cases, HTTPS features will be used; casting does not change the nature of the object.

Other case are client certificates in GAE - see Client Authentication by Certificate in GAE java queston.

*Weird thing is, that javadoc for URL.openConnection says:

If for the URL's protocol (such as HTTP or JAR), there exists a public, specialized URLConnection subclass belonging to one of the following packages or one of their subpackages: java.lang, java.io, java.util, java.net, the connection returned will be of that subclass. For example, for HTTP an HttpURLConnection will be returned, and for JAR a JarURLConnection will be returned.

(source: https://docs.oracle.com/javase/8/docs/api/java/net/URL.html#openConnection)

HttpsConnction is not in any of mentioned packages, so Google is free to provide any type it wants to. But such description gives a possibility to add HttpsURLConnection in the future to - for example - java.util package, and then AppEngine implementation will be no longer relevant. This is only speculation, and most probably it will never happen - but there is no guarantee! :)

Upvotes: 2

Related Questions