简体   繁体   English

使用Java进行HTTPS登录

[英]HTTPS Login using Java

I've a problem to login to a website via https . 我无法通过https登录到网站。 I wrote this code (it works) for http access: 我为http访问编写了此代码(它有效):

String user = user;
String password = psw;    

String authString = user + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);

URLConnection connection= url.openConnection();

connection.setRequestProperty("Authorization", "Basic " + authStringEnc);  
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");

connection.connect();

I'd like to do the same things but via https . 我想通过https做同样的事情。 Is it possible? 可能吗?

You can, please use 可以,请使用

HttpsURLConnection

Checkout sample program on http://www.mkyong.com/java/java-https-client-httpsurlconnection-example/ http://www.mkyong.com/java/java-https-client-httpsurlconnection-example/上的Checkout示例程序

When specifying your URL, make sure to pass "https://..." 指定URL时,请确保传递“ https:// ...”

url.openConnection();

will return you an object that has the type of the established connection. 将返回具有已建立连接类型的对象。 It will always be URLConnection, but it can be a class that extends URLConnection as well. 它始终是URLConnection,但也可以是扩展URLConnection的类。 Such classes are HttpURLConnection and HttpsURLConnection (and others). 这样的类是HttpURLConnection和HttpsURLConnection (及其他)。

You should verify that the returned object is of type HttpsURLConnection. 您应该验证返回的对象的类型为HttpsURLConnection。 And if it's not, you should stop the connection (in case you want to avoid non secure connections). 如果不是,则应停止连接(以防出现不安全的连接)。

if (connection instanceof HttpsURLConnection)

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

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