Example usage for org.apache.commons.httpclient.auth AuthenticationException AuthenticationException

List of usage examples for org.apache.commons.httpclient.auth AuthenticationException AuthenticationException

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.auth AuthenticationException AuthenticationException.

Prototype

public AuthenticationException() 

Source Link

Usage

From source file:org.pentaho.di.core.HTTPProtocol.java

/**
 * Performs a get on urlAsString using username and password as credentials.
 *
 * If the status code returned not -1 and 401 then the contents are returned. If the status code is 401 an
 * AuthenticationException is thrown./*from  w  w  w .j a va 2 s .co  m*/
 *
 * All other values of status code are not dealt with but logic can be added as needed.
 *
 * @param urlAsString
 * @param username
 * @param password
 * @param encoding
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
public String get(String urlAsString, String username, String password)
        throws MalformedURLException, IOException, AuthenticationException {

    HttpClient httpClient = SlaveConnectionManager.getInstance().createHttpClient();
    GetMethod getMethod = new GetMethod(urlAsString);
    if (!Const.isEmpty(username)) {
        httpClient.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        httpClient.getState().setCredentials(AuthScope.ANY, defaultcreds);
    }
    int statusCode = httpClient.executeMethod(getMethod);
    StringBuffer bodyBuffer = new StringBuffer();

    if (statusCode != -1) {
        if (statusCode != 401) {

            // the response
            InputStreamReader inputStreamReader = new InputStreamReader(getMethod.getResponseBodyAsStream());

            int c;
            while ((c = inputStreamReader.read()) != -1) {
                bodyBuffer.append((char) c);
            }
            inputStreamReader.close();

        } else {
            throw new AuthenticationException();
        }
    }

    // Display response
    return bodyBuffer.toString();
}