Java Tip: Basic Authentication with HttpURLConnection Java Astuce: l'authentification de base avec HttpURLConnection
Java provides a super simple, yet hidden from plain view, way to do basic authentication of HttpURLConnection / URLConnection. Java fournit un super simple, encore cachée de vue, manière de le faire de l'authentification de base HttpURLConnection / URLConnection.
Before making a connection add the following lines of code: Avant de faire une connexion ajoutez les lignes suivantes de code:
final String login ="..."; final String password ="..."; Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication (login, password.toCharArray()); } }); final String login ="..."; final String mot de passe ="..."; Authenticator.setDefault (new Authenticator () (private PasswordAuthentication getPasswordAuthentication () (return nouveau PasswordAuthentication (login, password.toCharArray ());)) ); This sets your default Authenticator which is called whenever authentication is required for any URLConnection. Ceci définit par défaut Authenticator qui est appelée chaque fois que l'authentification est requise pour toute URLConnection. Problem solved. Problème résolu.
Note: final is required for the inner class to access the variable. Note: final est requise pour l'intérieur classe pour accéder à la variable.
Authenticator is available since JDK 1.2 and yet very few information is there about it on the web. Authenticator est disponible depuis le JDK 1,2 et encore très peu d'informations existe-t-il à ce sujet sur le Web. Almost everyone recommend using a class from Sun package ( sun.misc.BASE64Encoder() ) and do the encoding manually. Presque tout le monde vous recommandons d'utiliser une classe de Sun paquet (sun.misc.BASE64Encoder ()) et faire l'encodage manuellement. None of this is required in the simple solution above. Rien de tout cela est exigé dans la solution simple ci-dessus.
The Java URLConnection API should have a setAuthenticator(Authenticator) method for making it easier to use this class in multi-threaded context where authentication is required. L'API Java URLConnection devrait avoir un setAuthenticator (Authenticator) méthode pour rendre plus facile à utiliser dans cette classe multi-threadé contexte où l'authentification est nécessaire.
Filed under Classé sous Headline News Headline News , How To Comment , Java Software Logiciel de Java , Programming Programmation , Tech Note Note technique , Web , Web Services Services Web | |
| |
RSS 2.0 RSS 2,0 | |
Trackback this Article | cet article |
Email this Article Envoyer cet article
You may also like to read Vous mai également à lire |



