Authentication Methods

Aus wiki
Version vom 18. August 2014, 09:41 Uhr von Christofbuechi (Diskussion | Beiträge)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
Wechseln zu: Navigation, Suche

Digest Authentication with HttpsUrlConnection

package com.company;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.PasswordAuthentication;
import java.net.URL;

public class Main {

   public static void main(String[] args) throws IOException {
       Authenticator.setDefault(new Authenticator() {
           protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication("user", "passwd".toCharArray());
           }
       });
       CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
       HttpsURLConnection con = (HttpsURLConnection) new URL(null, "http://httpbin.org/digest-auth/auth/user/passwd", new   sun.net.www.protocol.https.Handler()).openConnection();

        BufferedReader in = null;
        StringBuffer sb = new StringBuffer();
       in = new BufferedReader(new InputStreamReader(con.getInputStream()));
       String line;
       while ((line = in.readLine()) != null) {
           sb.append(line);
       }
       System.out.println(sb.toString());
   }
}

Output:

{  "authenticated": true,   "user": "user"}