简体   繁体   English

使用HttpURLConnection的Https网站

[英]Https Website using HttpURLConnection

I have a question regarding using an HttpUrlConnection with a https web service. 我有一个关于将HttpUrlConnection与https Web服务一起使用的问题。

Basically, we had previously written a bunch of web services to be used in an Android application that were all http calls. 基本上,我们之前已经编写了一堆要用于Android应用程序的Web服务,这些服务都是http调用。 We want to change those over to use https instead. 我们希望将其改为使用https。 Basically, what I'm concerned with, is will my existing code work properly? 基本上,我所关心的是,现有代码是否可以正常工作? I had previously created a connection like the following: 我以前创建了如下连接:

HttpURLConnection myConnection = (HttpURLConnection) myURL.openConnection();
myConnection.setConnectTimeout(TIMEOUT_MILLISEC);
myConnection.connect();

This appears to be working fine with the new https web services, but I'm wondering why I don't need to change it to something like this: 这似乎可以与新的https Web服务配合使用,但是我想知道为什么我不需要将其更改为以下内容:

HttpsURLConnection myConnection = (HttpsURLConnection) myURL.openConnection();
myConnection.setConnectTimeout(TIMEOUT_MILLISEC);
myConnection.setSSLSocketFactory(createSSLSocketFactory());
myConnection.connect();

I'm still planning on moving to a HttpsURLConnection instead, but I'm curious how older versions of our app will be affected by our intended changes. 我仍然打算改用HttpsURLConnection ,但是我很好奇我们的应用程序的旧版本将如何受到预期更改的影响。

Thanks for the help! 谢谢您的帮助!

In docs for HttpUrlConnection you will find: HttpUrlConnection的文档中,您将找到:

Calling openConnection() on a URL with the "https" scheme will return an HttpsURLConnection 使用“ https”方案在URL上调用openConnection()将返回HttpsURLConnection

But since HttpsUrlConnection extends from HttpUrlConnection, this code: 但是由于HttpsUrlConnection是从HttpUrlConnection扩展的,因此此代码:

HttpURLConnection myConnection = (HttpURLConnection) myURL.openConnection();

will NOT result in class cast exception if url is for https connection. 如果url用于https连接,将不会导致类强制转换异常。 You still can cast to HttpsUrlConnection - just for safety you can check with instanceof if url scheme should change. 您仍然可以强制转换为HttpsUrlConnection-出于安全考虑,您可以使用instanceof检查url方案是否应该更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM