Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.Authenticator;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLConnection;
- import org.apache.commons.codec.binary.Base64;
- public class ConnectToUrlUsingBasicAuthentication {
- public static void main(String[] args) {
- try {
- String webPage = "http://servername/webservice/ABC.asmx/GetStudentReport";
- String name = "domain.lab\sachin";
- String password = "Password123";
- //NtlmHandler handler = new NtlmHandler();
- Authenticator.setDefault(new NtlmAuthenticator(name, password));
- String authString = name + ":" + password;
- System.out.println("auth string: " + authString);
- byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
- String authStringEnc = new String(authEncBytes);
- System.out.println("Base64 encoded auth string: " + authStringEnc);
- URL url = new URL(webPage);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- //conn.setRequestProperty("Authorization", "Basic " +authStringEnc );
- conn.connect();
- System.out.println("Response Code: " + conn.getResponseCode() );
- URLConnection urlConnection = url.openConnection();
- urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
- InputStream is = urlConnection.getInputStream();
- InputStreamReader isr = new InputStreamReader(is);
- int numCharsRead;
- char[] charArray = new char[1024];
- StringBuffer sb = new StringBuffer();
- while ((numCharsRead = isr.read(charArray)) > 0) {
- sb.append(charArray, 0, numCharsRead);
- }
- String result = sb.toString();
- System.out.println("*** BEGIN ***");
- System.out.println(result);
- System.out.println("*** END ***");
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- import java.net.Authenticator;
- import java.net.PasswordAuthentication;
- public class NtlmAuthenticator extends Authenticator {
- private final String username;
- private final char[] password;
- public NtlmAuthenticator(final String username, final String password) {
- super();
- this.username = new String(username);
- this.password = password.toCharArray();
- }
- @Override
- public PasswordAuthentication getPasswordAuthentication() {
- System.out.println("Scheme:" + getRequestingScheme() );
- System.out.println("Host:" + getRequestingHost() );
- PasswordAuthentication pa = new PasswordAuthentication(username, password);
- System.out.println("UserName:" + pa.getUserName() );
- System.out.println("Password:" + pa.getPassword().toString() );
- return pa;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement