Java 类org.apache.commons.httpclient.auth.AuthScope 实例源码

项目:oscm    文件:BasicAuthLoader.java   
/**
 * Retrieves the content under the given URL with username and passwort
 * authentication.
 * 
 * @param url
 *            the URL to read
 * @param username
 * @param password
 * @return the read content.
 * @throws IOException
 *             if an I/O exception occurs.
 */
private static byte[] getUrlContent(URL url, String username,
        String password) throws IOException {
    final HttpClient client = new HttpClient();

    // Set credentials:
    client.getParams().setAuthenticationPreemptive(true);
    final Credentials credentials = new UsernamePasswordCredentials(
            username, password);
    client.getState()
            .setCredentials(
                    new AuthScope(url.getHost(), url.getPort(),
                            AuthScope.ANY_REALM), credentials);

    // Retrieve content:
    final GetMethod method = new GetMethod(url.toString());
    final int status = client.executeMethod(method);
    if (status != HttpStatus.SC_OK) {
        throw new IOException("Error " + status + " while retrieving "
                + url);
    }
    return method.getResponseBody();
}
项目:convertigo-engine    文件:WsReference.java   
private static void tryAuthentication(RemoteFileReference wsReference) throws Exception {
    URL urlToConnect = wsReference.getUrl();
    String wsdlUrl = wsReference.getUrlpath();
    String username = wsReference.getAuthUser();
    String password = wsReference.getAuthPassword();

       HttpClient client = new HttpClient();

    client.getState().setCredentials(
            new AuthScope(urlToConnect.getHost(), urlToConnect.getPort()),
            new UsernamePasswordCredentials(username, password)
    );

       GetMethod get = new GetMethod(wsdlUrl);
       get.setDoAuthentication( true );

       int statuscode = client.executeMethod(get);

       if (statuscode == HttpStatus.SC_UNAUTHORIZED) {
        throw new Exception(HttpStatus.SC_UNAUTHORIZED + " - Unauthorized connection!");
       }
}
项目:lams    文件:HTTPMetadataProvider.java   
/**
 * Constructor.
 * 
 * @param metadataURL the URL to fetch the metadata
 * @param requestTimeout the time, in milliseconds, to wait for the metadata server to respond
 * 
 * @throws MetadataProviderException thrown if the URL is not a valid URL or the metadata can not be retrieved from
 *             the URL
 */
@Deprecated
public HTTPMetadataProvider(String metadataURL, int requestTimeout) throws MetadataProviderException {
    super();
    try {
        metadataURI = new URI(metadataURL);
    } catch (URISyntaxException e) {
        throw new MetadataProviderException("Illegal URL syntax", e);
    }

    HttpClientParams clientParams = new HttpClientParams();
    clientParams.setSoTimeout(requestTimeout);
    httpClient = new HttpClient(clientParams);
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(requestTimeout);
    authScope = new AuthScope(metadataURI.getHost(), metadataURI.getPort());

}
项目:lams    文件:HTTPMetadataProvider.java   
/**
 * Constructor.
 * 
 * @param client HTTP client used to pull in remote metadata
 * @param backgroundTaskTimer timer used to schedule background metadata refresh tasks
 * @param metadataURL URL to the remove remote metadata
 * 
 * @throws MetadataProviderException thrown if the HTTP client is null or the metadata URL provided is invalid
 */
public HTTPMetadataProvider(Timer backgroundTaskTimer, HttpClient client, String metadataURL)
        throws MetadataProviderException {
    super(backgroundTaskTimer);

    if (client == null) {
        throw new MetadataProviderException("HTTP client may not be null");
    }
    httpClient = client;

    try {
        metadataURI = new URI(metadataURL);
    } catch (URISyntaxException e) {
        throw new MetadataProviderException("Illegal URL syntax", e);
    }

    authScope = new AuthScope(metadataURI.getHost(), metadataURI.getPort());
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:AnonymousAccessTest.java   
public void testAnonymousContent() throws Exception {
    // disable credentials -> anonymous session
    final URL url = new URL(HTTP_BASE_URL);
    final AuthScope scope = new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM);
    httpClient.getParams().setAuthenticationPreemptive(false);
    httpClient.getState().setCredentials(scope, null);

    try {
        assertContent();
    } finally {
        // re-enable credentials -> admin session
        httpClient.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials("admin", "admin");
        httpClient.getState().setCredentials(scope, defaultcreds);
    }
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:AuthenticationResponseCodeTest.java   
@Test
public void testValidatingIncorrectHttpBasicCredentials() throws Exception {

    // assume http and webdav are on the same host + port
    URL url = new URL(HttpTest.HTTP_BASE_URL);
    Credentials defaultcreds = new UsernamePasswordCredentials("garbage", "garbage");
    H.getHttpClient().getState()
            .setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds);

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_validate", "true"));
    HttpMethod post = H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check",
            HttpServletResponse.SC_FORBIDDEN, params, null);
    assertXReason(post);

    HttpMethod get = H.assertHttpStatus(HttpTest.HTTP_BASE_URL + "/?j_validate=true",
            HttpServletResponse.SC_FORBIDDEN);
    assertXReason(get);
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:AuthenticationResponseCodeTest.java   
@Test
public void testPreventLoopIncorrectHttpBasicCredentials() throws Exception {

    // assume http and webdav are on the same host + port
    URL url = new URL(HttpTest.HTTP_BASE_URL);
    Credentials defaultcreds = new UsernamePasswordCredentials("garbage", "garbage");
    H.getHttpClient().getState()
            .setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds);

    final String requestUrl = HttpTest.HTTP_BASE_URL + "/junk?param1=1";
    HttpMethod get = new GetMethod(requestUrl);
    get.setRequestHeader("Referer", requestUrl);
    get.setRequestHeader("User-Agent", "Mozilla/5.0 Sling Integration Test");
    int status = H.getHttpClient().executeMethod(get);
    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, status);
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:AuthenticatedTestUtil.java   
/** Verify that given URL returns expectedStatusCode
 * @throws IOException */
public void assertAuthenticatedHttpStatus(Credentials creds, String urlString, int expectedStatusCode, String assertMessage) throws IOException {
    URL baseUrl = new URL(HTTP_BASE_URL);
    AuthScope authScope = new AuthScope(baseUrl.getHost(), baseUrl.getPort(), AuthScope.ANY_REALM);
    GetMethod getMethod = new GetMethod(urlString);
    getMethod.setDoAuthentication(true);
    Credentials oldCredentials = httpClient.getState().getCredentials(authScope);
    try {
        httpClient.getState().setCredentials(authScope, creds);

        final int status = httpClient.executeMethod(getMethod);
        if(assertMessage == null) {
            assertEquals(urlString,expectedStatusCode, status);
        } else {
            assertEquals(assertMessage, expectedStatusCode, status);
        }
    } finally {
        httpClient.getState().setCredentials(authScope, oldCredentials);
    }
}
项目:lib-commons-httpclient    文件:HttpState.java   
/**
 * Find matching {@link Credentials credentials} for the given authentication scope.
 *
 * @param map the credentials hash map
 * @param token the {@link AuthScope authentication scope}
 * @return the credentials 
 * 
 */
private static Credentials matchCredentials(final HashMap map, final AuthScope authscope) {
    // see if we get a direct hit
    Credentials creds = (Credentials)map.get(authscope);
    if (creds == null) {
        // Nope.
        // Do a full scan
        int bestMatchFactor  = -1;
        AuthScope bestMatch  = null;
        Iterator items = map.keySet().iterator();
        while (items.hasNext()) {
            AuthScope current = (AuthScope)items.next();
            int factor = authscope.match(current);
            if (factor > bestMatchFactor) {
                bestMatchFactor = factor;
                bestMatch = current;
            }
        }
        if (bestMatch != null) {
            creds = (Credentials)map.get(bestMatch);
        }
    }
    return creds;
}
项目:lib-commons-httpclient    文件:TestProxyWithRedirect.java   
public void testAuthProxyWithRedirect() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
    this.server.setHttpService(new BasicRedirectService("/"));
    this.proxy.requireAuthentication(creds, "test", true);

    GetMethod get = new GetMethod("/redirect/");
    try {
        this.client.executeMethod(get);
        assertEquals(HttpStatus.SC_OK, get.getStatusCode());
    } finally {
        get.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:TestProxyWithRedirect.java   
public void testAuthProxyWithCrossSiteRedirect() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
    this.server.setHttpService(new BasicRedirectService(
            "http://127.0.0.1:" + this.server.getLocalPort()));

    this.proxy.requireAuthentication(creds, "test", true);

    GetMethod get = new GetMethod("/redirect/");
    try {
        this.client.executeMethod(get);
        assertEquals(HttpStatus.SC_OK, get.getStatusCode());
    } finally {
        get.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:TestProxyWithRedirect.java   
public void testPreemptiveAuthProxyWithCrossSiteRedirect() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
    this.client.getParams().setAuthenticationPreemptive(true);
    this.server.setHttpService(new BasicRedirectService(
            "http://127.0.0.1:" + this.server.getLocalPort()));

    this.proxy.requireAuthentication(creds, "test", true);

    GetMethod get = new GetMethod("/redirect/");
    try {
        this.client.executeMethod(get);
        assertEquals(HttpStatus.SC_OK, get.getStatusCode());
    } finally {
        get.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:TestHttps.java   
/**
 * Direct unit test for host versification in SSL.
 * The test has been proposed as a patch in <a href="https://issues.apache.org/jira/browse/HTTPCLIENT-1265">HTTPCLIENT-1265</a>
 */
@Issue("SECURITY-555")
public void testHostNameValidation() {
    HttpClient client = new HttpClient();
    if (PROXY_HOST != null) {
        if (PROXY_USER != null) {
            HttpState state = client.getState();
            state.setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                    PROXY_USER, PROXY_PASS));
        }
        client.getHostConfiguration().setProxy(PROXY_HOST, Integer.parseInt(PROXY_PORT));
    }
    GetMethod method = new GetMethod(_urlWithIp);

    try {
        client.executeMethod(method);
        fail("Invalid hostname not detected");
    } catch (SSLException e) {
        assertTrue("Connection with a invalid server certificate rejected", true);
    } catch (Throwable t) {
        t.printStackTrace();
        fail("Unexpected exception" + t.getMessage());
    }
}
项目:lib-commons-httpclient    文件:TestProxy.java   
/**
 * Tests GET via non-authenticating proxy + host auth + connection keep-alive 
 */
public void testGetHostAuthConnKeepAlive() throws Exception {

    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    this.client.getState().setCredentials(AuthScope.ANY, creds);

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    this.server.setRequestHandler(handlerchain);

    GetMethod get = new GetMethod("/");
    try {
        this.client.executeMethod(get);
        assertEquals(HttpStatus.SC_OK, get.getStatusCode());
    } finally {
        get.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:TestProxy.java   
/**
 * Tests GET via non-authenticating proxy + host auth + connection close 
 */
public void testGetHostAuthConnClose() throws Exception {

    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    this.client.getState().setCredentials(AuthScope.ANY, creds);

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    this.server.setRequestHandler(handlerchain);

    GetMethod get = new GetMethod("/");
    try {
        this.client.executeMethod(get);
        assertEquals(HttpStatus.SC_OK, get.getStatusCode());
    } finally {
        get.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:TestProxy.java   
/**
 * Tests GET via non-authenticating proxy + invalid host auth 
 */
public void testGetHostInvalidAuth() throws Exception {

    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    this.client.getState().setCredentials(AuthScope.ANY, creds);

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    this.client.getState().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("testuser", "wrongstuff"));

    this.server.setRequestHandler(handlerchain);

    GetMethod get = new GetMethod("/");
    try {
        this.client.executeMethod(get);
        assertEquals(HttpStatus.SC_UNAUTHORIZED, get.getStatusCode());
    } finally {
        get.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:TestProxy.java   
/**
 * Tests GET via authenticating proxy + host auth + connection keep-alive 
 */
public void testGetProxyAuthHostAuthConnKeepAlive() throws Exception {

    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    this.client.getState().setCredentials(AuthScope.ANY, creds);
    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    this.server.setRequestHandler(handlerchain);

    this.proxy.requireAuthentication(creds, "test", true);

    GetMethod get = new GetMethod("/");
    try {
        this.client.executeMethod(get);
        assertEquals(HttpStatus.SC_OK, get.getStatusCode());
    } finally {
        get.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:TestProxy.java   
/**
 * Tests GET via authenticating proxy
 */
public void testGetAuthProxy() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
    this.server.setHttpService(new FeedbackService());

    this.proxy.requireAuthentication(creds, "test", true);

    GetMethod get = new GetMethod("/");
    try {
        this.client.executeMethod(get);
        assertEquals(HttpStatus.SC_OK, get.getStatusCode());
    } finally {
        get.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:TestProxy.java   
/**
 * Tests GET via authenticating proxy + host auth + connection close 
 */
public void testGetProxyAuthHostAuthConnClose() throws Exception {

    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    this.client.getState().setCredentials(AuthScope.ANY, creds);
    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    this.server.setRequestHandler(handlerchain);

    this.proxy.requireAuthentication(creds, "test", true);

    GetMethod get = new GetMethod("/");
    try {
        this.client.executeMethod(get);
        assertEquals(HttpStatus.SC_OK, get.getStatusCode());
    } finally {
        get.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:TestProxy.java   
/**
 * Tests GET via authenticating proxy + invalid host auth 
 */
public void testGetProxyAuthHostInvalidAuth() throws Exception {

    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    this.client.getState().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("testuser", "wrongstuff"));
    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);

    this.server.setRequestHandler(handlerchain);

    this.proxy.requireAuthentication(creds, "test", true);

    GetMethod get = new GetMethod("/");
    try {
        this.client.executeMethod(get);
        assertEquals(HttpStatus.SC_UNAUTHORIZED, get.getStatusCode());
    } finally {
        get.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:TestProxy.java   
/**
 * Tests POST via non-authenticating proxy + host auth + connection keep-alive 
 */
public void testPostHostAuthConnKeepAlive() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    this.client.getState().setCredentials(AuthScope.ANY, creds);

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    this.server.setRequestHandler(handlerchain);

    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:TestProxy.java   
/**
 * Tests POST via non-authenticating proxy + host auth + connection close 
 */
public void testPostHostAuthConnClose() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    this.client.getState().setCredentials(AuthScope.ANY, creds);

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    this.server.setRequestHandler(handlerchain);

    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:TestProxy.java   
/**
 * Tests POST via non-authenticating proxy + invalid host auth 
 */
public void testPostHostInvalidAuth() throws Exception {

    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    this.client.getState().setCredentials(AuthScope.ANY, creds);

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    this.client.getState().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("testuser", "wrongstuff"));

    this.server.setRequestHandler(handlerchain);

    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_UNAUTHORIZED, post.getStatusCode());
    } finally {
        post.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:TestProxy.java   
/**
 * Tests POST via authenticating proxy
 */
public void testPostAuthProxy() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
    this.server.setHttpService(new FeedbackService());

    this.proxy.requireAuthentication(creds, "test", true);

    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:TestProxy.java   
/**
 * Tests POST via authenticating proxy + host auth + connection keep-alive 
 */
public void testPostProxyAuthHostAuthConnKeepAlive() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    this.client.getState().setCredentials(AuthScope.ANY, creds);
    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    this.server.setRequestHandler(handlerchain);

    this.proxy.requireAuthentication(creds, "test", true);

    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:TestProxy.java   
/**
 * Tests POST via authenticating proxy + host auth + connection close 
 */
public void testPostProxyAuthHostAuthConnClose() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    this.client.getState().setCredentials(AuthScope.ANY, creds);
    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    this.server.setRequestHandler(handlerchain);

    this.proxy.requireAuthentication(creds, "test", true);

    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:TestProxy.java   
public void testPreemptiveAuthProxy() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
    this.client.getParams().setAuthenticationPreemptive(true);
    this.server.setHttpService(new FeedbackService());

    this.proxy.requireAuthentication(creds, "test", true);

    GetMethod get = new GetMethod("/");
    try {
        this.client.executeMethod(get);
        assertEquals(HttpStatus.SC_OK, get.getStatusCode());
        if (isUseSSL()) {
            assertNull(get.getRequestHeader("Proxy-Authorization"));
        } else {
            assertNotNull(get.getRequestHeader("Proxy-Authorization"));
        }
    } finally {
        get.releaseConnection();
    }
}
项目:lib-commons-httpclient    文件:TestProxy.java   
/**
 * Tests GET via authenticating proxy + host auth + HTTP/1.0 
 */
public void testGetProxyAuthHostAuthHTTP10() throws Exception {

    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    this.client.getState().setCredentials(AuthScope.ANY, creds);
    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
    this.client.getParams().setVersion(HttpVersion.HTTP_1_0);

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    this.server.setRequestHandler(handlerchain);

    this.proxy.requireAuthentication(creds, "test", false);

    GetMethod get = new GetMethod("/");
    try {
        this.client.executeMethod(get);
        assertEquals(HttpStatus.SC_OK, get.getStatusCode());
    } finally {
        get.releaseConnection();
    }
}
项目:GeoCrawler    文件:Http.java   
/**
 * Returns an authentication scope for the specified <code>host</code>,
 * <code>port</code>, <code>realm</code> and <code>scheme</code>.
 * 
 * @param host
 *          Host name or address.
 * @param port
 *          Port number.
 * @param realm
 *          Authentication realm.
 * @param scheme
 *          Authentication scheme.
 */
private static AuthScope getAuthScope(String host, int port, String realm,
    String scheme) {

  if (host.length() == 0)
    host = null;

  if (port < 0)
    port = -1;

  if (realm.length() == 0)
    realm = null;

  if (scheme.length() == 0)
    scheme = null;

  return new AuthScope(host, port, realm, scheme);
}
项目:scribe    文件:ZDCRMTest.java   
public final void getUsers(final String userId, final String password, final String crmURL) {
  final GetMethod get = new GetMethod("http://" + crmURL + "/users.xml");

  get.addRequestHeader("Content-Type", "application/xml");
  final HttpClient httpclient = new HttpClient();

  /* Set credentials */
  httpclient.getState().setCredentials(new AuthScope(crmURL, 80), new UsernamePasswordCredentials(userId, password));

  try {

    int result = httpclient.executeMethod(get);
    System.out.println("Response status code: " + result);
    System.out.println("Response body: " + get.getResponseBodyAsString());
    cookie = get.getResponseHeader("Set-Cookie").getValue();
    System.out.println(cookie);
  } catch (final Exception exception) {
    System.err.println(exception);
  } finally {
    get.releaseConnection();
  }
}
项目:scribe    文件:ZDCRMTest.java   
public final void getTickets(final String userId, final String password, final String crmURL) {
  final GetMethod get = new GetMethod("http://" + crmURL + "/tickets.xml");

  get.addRequestHeader("Content-Type", "application/xml");
  final HttpClient httpclient = new HttpClient();

  /* Set credentials */
  httpclient.getState().setCredentials(new AuthScope(crmURL, 80), new UsernamePasswordCredentials(userId, password));

  try {
    int result = httpclient.executeMethod(get);
    System.out.println("Response status code: " + result);
    System.out.println("Response body: " + get.getResponseBodyAsString());
  } catch (final Exception exception) {
    System.err.println(exception);
  } finally {
    get.releaseConnection();
  }
}
项目:scribe    文件:ZDCRMTest.java   
public final void search(final String userId, final String password, final String crmURL, final String query) {
  final GetMethod get = new GetMethod("http://" + crmURL + "/search.xml");

  get.addRequestHeader("Content-Type", "application/xml");
  get.addRequestHeader(
      "Cookie",
      "_zendesk_session=BAh7DiIOaXNfbW9iaWxlRjoPc2Vzc2lvbl9pZCIlYmNmNGVlMjk4YWNlNDU3ZDM0YjJjOGU3MDU1NGQ1NjEiHHdhcmRlbi51c2VyLmRlZmF1bHQua2V5aQQBh10EOg1hdXRoX3ZpYSISQmFzaWNTdHJhdGVneToPdXBkYXRlZF9hdGwrB3kGTE46FWF1dGhlbnRpY2F0ZWRfYXRsKwd5BkxOIhN3YXJkZW4ubWVzc2FnZXsAOgxhY2NvdW50aQPKdQE6B2lkIhRjbnRscHlzeTRjMG9zcGg%3D--31e3c6f26da13b568a65872d067d1da2942ace01; path=/; HttpOnly, oid_user=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT");
  final HttpClient httpclient = new HttpClient();

  /* Set credentials */
  httpclient.getState().setCredentials(new AuthScope(crmURL, 80), new UsernamePasswordCredentials(userId, password));
  try {

    /* Set request parameter */
    get.setQueryString(new NameValuePair[] {new NameValuePair("query", query)});

    int result = httpclient.executeMethod(get);
    System.out.println("Response status code: " + result);
    System.out.println("Response body: " + get.getResponseBodyAsString());

  } catch (final Exception exception) {
    System.err.println(exception);
  } finally {
    get.releaseConnection();
  }
}
项目:scribe    文件:ZDCRMTest.java   
public final void getEntries(final String userId, final String password, final String crmURL) {
  final GetMethod get = new GetMethod("http://" + crmURL + "/entries.xml");

  get.addRequestHeader("Content-Type", "application/xml");
  final HttpClient httpclient = new HttpClient();

  /* Set credentials */
  httpclient.getState().setCredentials(new AuthScope(crmURL, 80), new UsernamePasswordCredentials(userId, password));

  try {

    int result = httpclient.executeMethod(get);
    System.out.println("Response status code: " + result);
    System.out.println("Response body: " + get.getResponseBodyAsString());

  } catch (final Exception exception) {
    System.err.println(exception);
  } finally {
    get.releaseConnection();
  }
}
项目:hermes    文件:HttpSender.java   
/**
 * Set to use the basic authentication when calling the web service.
 * 
 * @param username The user-name for basic authentication. 
 * @param password The password for basic authentication.
 * 
 * @throws NullPointerException 
 *          When the user-name or password is null.         
 */
public void setBasicAuthentication(final String username, final String password)
{
    if (username == null || username.equals(""))
        throw new NullPointerException("Missing 'username' for authentication.");
    if (password == null)
        throw new NullPointerException("Missing 'password' for authentication.");

    this.delegationClient.getState().setCredentials(
        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
        new UsernamePasswordCredentials(username, password));

    // Use BASIC-Auth immediately.
    this.delegationClient.getParams().setAuthenticationPreemptive(true);
    this.isAuthRequired = true;
}
项目:jenkins-telegram-plugin    文件:StandardTelegramService.java   
protected HttpClient getHttpClient() {
    HttpClient client = new HttpClient();
    Jenkins instance = Jenkins.getInstance();
    if (instance != null) {
        ProxyConfiguration proxy = instance.proxy;
        if (proxy != null) {
            client.getHostConfiguration().setProxy(proxy.name, proxy.port);
            String username = proxy.getUserName();
            String password = proxy.getPassword();
            // Consider it to be passed if username specified. Sufficient?
            if (username != null && !"".equals(username.trim())) {
                logger.info("Using proxy authentication (user=" + username + ")");
                // http://hc.apache.org/httpclient-3.x/authentication.html#Proxy_Authentication
                // and
                // http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/BasicAuthenticationExample.java?view=markup
                client.getState().setProxyCredentials(AuthScope.ANY,
                        new UsernamePasswordCredentials(username, password));
            }
        }
    }
    return client;
}
项目:cosmic    文件:UriUtils.java   
public static InputStream getInputStreamFromUrl(final String url, final String user, final String password) {

        try {
            final Pair<String, Integer> hostAndPort = validateUrl(url);
            final HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager());
            if ((user != null) && (password != null)) {
                httpclient.getParams().setAuthenticationPreemptive(true);
                final Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
                httpclient.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
                s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
            }
            // Execute the method.
            final GetMethod method = new GetMethod(url);
            final int statusCode = httpclient.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                s_logger.error("Failed to read from URL: " + url);
                return null;
            }

            return method.getResponseBodyAsStream();
        } catch (final Exception ex) {
            s_logger.error("Failed to read from URL: " + url);
            return null;
        }
    }
项目:ecommerce-framework    文件:AdminProxyController.java   
@PostConstruct
public void initialize() throws IOException {

    if ( StringUtils.isNotEmpty(this.fredhopperBaseUrl) ) {
        this.fredhopperAdminUrl = this.fredhopperBaseUrl + ADMIN_URL;
        this.connectionManager =
                new MultiThreadedHttpConnectionManager();
        this.client = new HttpClient(connectionManager);

        if (this.accessUsername != null && !this.accessUsername.isEmpty()) {
            Credentials credentials = new UsernamePasswordCredentials(this.accessUsername, this.accessPassword);
            client.getState().setCredentials(AuthScope.ANY, credentials);
        }
        this.login();
        this.lastAccessTime = System.currentTimeMillis();
        this.isInitialized = true;
    }
}
项目:anyline    文件:HttpUtil.java   
private synchronized void init() {
    client = new HttpClient(new MultiThreadedHttpConnectionManager());
    HttpClientParams params = client.getParams();
    if (encode != null && !encode.trim().equals("")) {
        params.setParameter("http.protocol.content-charset", encode);
        params.setContentCharset(encode);
    }
    if (timeout > 0) {
        params.setSoTimeout(timeout);
    }
    if (null != proxy) {
        HostConfiguration hc = new HostConfiguration();
        hc.setProxy(proxy.getHost(), proxy.getPort());
        client.setHostConfiguration(hc);
        client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxy.getUser(), proxy.getPassword()));
    }
    initialized = true;
}
项目:intellij-ce-playground    文件:BaseRepositoryImpl.java   
protected void configureHttpClient(HttpClient client) {
  client.getParams().setConnectionManagerTimeout(3000);
  client.getParams().setSoTimeout(TaskSettings.getInstance().CONNECTION_TIMEOUT);
  if (isUseProxy()) {
    HttpConfigurable proxy = HttpConfigurable.getInstance();
    client.getHostConfiguration().setProxy(proxy.PROXY_HOST, proxy.PROXY_PORT);
    if (proxy.PROXY_AUTHENTICATION) {
      AuthScope authScope = new AuthScope(proxy.PROXY_HOST, proxy.PROXY_PORT);
      Credentials credentials = getCredentials(proxy.PROXY_LOGIN, proxy.getPlainProxyPassword(), proxy.PROXY_HOST);
      client.getState().setProxyCredentials(authScope, credentials);
    }
  }
  if (isUseHttpAuthentication()) {
    client.getParams().setCredentialCharset("UTF-8");
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(getUsername(), getPassword()));
  }
  else {
    client.getState().clearCredentials();
    client.getParams().setAuthenticationPreemptive(false);
  }
}
项目:development    文件:PortFactory.java   
/**
 * Retrieves the content under the given URL with username and passwort
 * authentication.
 * 
 * @param url
 * @param username
 * @param password
 * @return
 * @throws IOException
 */
private static byte[] getUrlContent(URL url, String username,
        String password) throws IOException {
    final HttpClient client = new HttpClient();

    // Set credentials:
    client.getParams().setAuthenticationPreemptive(true);
    final Credentials credentials = new UsernamePasswordCredentials(
            username, password);
    client.getState()
            .setCredentials(
                    new AuthScope(url.getHost(), url.getPort(),
                            AuthScope.ANY_REALM), credentials);

    // Retrieve content:
    final GetMethod method = new GetMethod(url.toString());
    final int status = client.executeMethod(method);
    if (status != HttpStatus.SC_OK) {
        throw new IOException("Error " + status + " while retrieving "
                + url);
    }
    return method.getResponseBody();
}