【发布时间】:2018-04-24 14:51:12
【问题描述】:
SSL 新手总数。我知道我应该使用 HTTPS SSL (/TLS?) 将我的数据从我的客户端应用程序发送到我的服务器。或者至少这是我想做的。
我之前在 Java 中的实现使用了HttpURLConnection,看起来像这样:
HttpURLConnection conn = null;
try
{
URL url = new URL(urlString);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(dataString);
osw.flush();
osw.close();
os.close();
conn.connect();
if(conn.getResponseCode() != 200)
throw new MyServerException();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output);
}
if(conn != null)
conn.disconnect();
return sb.toString();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ProtocolException e) {
e.printStackTrace();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if(conn != null)
conn.disconnect();
}
throw new MyServerException();
... 这很好用。我找到了this web page,这表明我需要做的就是将我的HttpURLConnection 切换到HttpsURLConnection,一切都应该可以正常工作。
另一方面,在我服务器的 cPanel 上,我发现了一个 Lets Encrypt 部分,它使我能够将证书应用到我的服务器域。
除其他外,设置此设置会生成PEM-Encoded Certificate 和PEM-Encoded Issuer 证书。
但后来我有点难过。我只是假设我上面的代码更新为使用HttpsURLConnection 有效吗?我怎么知道它在工作。例如,如果我从我的 cPanel 中删除已颁发的证书,那么上面的代码仍然有效...
发布后我发现的事情
如果我将urlString 设为http,它会抛出异常,而如果它是https 地址则不会,所以我猜这很好。
另外,这个this post 表明我在正确的轨道上,因为我没有收到那里建议的任何错误,而且没有人提到这样做是错误的方式。
Of possible interest,实际上指出“SSL 现在称为传输层安全性 (TLS)”,这已经简化了事情。
This looks like a great 文章。我还注意到,除了 Lets Encrypt 选项之外,我们还必须在 cPanel 上设置 SSL/TLS。确实有道理,原来没看到。 更多: 原来 Lets Encrypt 是一项免费服务,它为您提供自动使用的证书,而不是从服务提供商处购买。但是,您也可以签署自己的免费证书,但不会被任何受信任的证书颁发机构 (CA) “认可”。
【问题讨论】:
标签: java ssl-certificate httpsurlconnection