使用 java 类 HttpsURLConnection [英] Using java class HttpsURLConnection

查看:28
本文介绍了使用 java 类 HttpsURLConnection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一小段代码,它基本上实现了一个 HTTP 客户端,即它发布请求并与重新响应一起工作.只要 HTTP 是一切都很好.出于某种原因,我现在必须支持HTTPS 也是.所以这里是我为了打开连接所做的简要说明:

 URL url = new URL(serverAddress);HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();

这失败了,说明:

sun.net.www.protocol.https.HttpsURLConnectionImpl 无法转换为 com.sun.net.ssl.HttpsURLConnection

我想这有点微不足道,但我只是不明白我做错了什么...谷歌搜索,代码看起来正确 - 不是吗?

感谢您的任何想法!

解决方案

保留它

I have a small piece of code which basically impements a HTTP-Client, i.e. it POSTS request and works with re RESPONSE. As long as HTTP is concenerned everthing work well. For some reason I now have to support HTTPS too. So here is briefly what I do in order to get a connection opened:

 URL url = new URL(serverAddress);
 HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();

This fails, stating:

sun.net.www.protocol.https.HttpsURLConnectionImpl cannot be cast to com.sun.net.ssl.HttpsURLConnection

I guess this is kinda trivial, but I just don't get what I'm doing wrong in this one... Googled it, and the code just looks right - not?

any ideas are appreciated!

解决方案

Just keep it java.net.URLConnection or cast it to java.net.HttpURLConnection instead. Both offers methods to do the desired task as good.


A side remark unrelated to the technical problem: you should never explicitly import/use Sun Java SE implementation specific classes in your code. Those are undocumented classes and are subject to changes which may cause your code break when you upgrade the JVM. On the other hand, your code may also break when you run it at a different brand JVM.


Update: since you seem to accidentally have imported it, go to Window > Preferences > Java > Appearance > Type Filters and Add com.sun.* and sun.* to the list. This way you won't ever import them accidentally:

这篇关于使用 java 类 HttpsURLConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆