Skip to content

Instantly share code, notes, and snippets.

@ezhov-da
Last active March 10, 2019 12:14
Show Gist options
  • Save ezhov-da/30e76b32f94201ee4a8f0859f87f256f to your computer and use it in GitHub Desktop.
Save ezhov-da/30e76b32f94201ee4a8f0859f87f256f to your computer and use it in GitHub Desktop.
авторизация
//https://examples.javacodegeeks.com/core-java/net/authenticator/access-password-protected-url-with-authenticator/
//https://docs.oracle.com/javase/6/docs/technotes/guides/net/http-auth.html
package com.javacodegeeks.snippets.core;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
public class AccessPasswordProtectedURLWithAuthenticator {
public static void main(String[] args) {
try {
// Sets the authenticator that will be used by the networking code
// when a proxy or an HTTP server asks for authentication.
Authenticator.setDefault(new CustomAuthenticator());
URL url = new URL("http://www.secure-site-example.com:80/");
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
catch (MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
}
catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
}
}
public static class CustomAuthenticator extends Authenticator {
// Called when password authorization is needed
protected PasswordAuthentication getPasswordAuthentication() {
// Get information about the request
String prompt = getRequestingPrompt();
String hostname = getRequestingHost();
InetAddress ipaddr = getRequestingSite();
int port = getRequestingPort();
String username = "username";
String password = "password";
// Return the information (a data holder that is used by Authenticator)
return new PasswordAuthentication(username, password.toCharArray());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment