简体   繁体   中英

HTTPS Login using Java

I've a problem to login to a website via https . I wrote this code (it works) for http access:

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 . Is it possible?

You can, please use

HttpsURLConnection

Checkout sample program on http://www.mkyong.com/java/java-https-client-httpsurlconnection-example/

When specifying your URL, make sure to pass "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. Such classes are HttpURLConnection and HttpsURLConnection (and others).

You should verify that the returned object is of type HttpsURLConnection. And if it's not, you should stop the connection (in case you want to avoid non secure connections).

if (connection instanceof HttpsURLConnection)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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