Example usage for org.apache.http.client.protocol HttpClientContext create

List of usage examples for org.apache.http.client.protocol HttpClientContext create

Introduction

In this page you can find the example usage for org.apache.http.client.protocol HttpClientContext create.

Prototype

public static HttpClientContext create() 

Source Link

Usage

From source file:org.wso2.apim.billing.clients.DASRestClient.java

/**
 * Do a post request to the DAS REST//ww  w  . j  a v  a  2  s .co m
 *
 * @param request lucene json request
 * @param url     DAS rest api location
 * @return return the HttpResponse after the request sent
 * @throws IOException throw if the connection exception occur
 */
public CloseableHttpResponse doPost(SearchRequestBean request, String url) throws IOException {
    String json = gson.toJson(request);
    System.out.println(json);
    if (log.isDebugEnabled()) {
        log.debug("Sending Lucene Query : " + json);
    }
    HttpPost postRequest = new HttpPost(url);
    HttpContext context = HttpClientContext.create();

    //get the encoded basic authentication
    String cred = encodeCredentials(this.user, this.pass);
    postRequest.addHeader(HTTP_AUTH_HEADER_NAME, HTTP_AUTH_HEADER_TYPE + ' ' + cred);
    StringEntity input = new StringEntity(json);
    input.setContentType(APPLICATION_JSON);
    postRequest.setEntity(input);

    //send the request
    return httpClient.execute(postRequest, context);
}

From source file:securitytools.veracode.VeracodeAsyncClient.java

/**
 * Constructs a new asynchronous VeracodeClient using the specified
 * configuration./* www  .ja  v  a 2 s.c  o  m*/
 *
 * @param credentials Credentials used to access Veracode services.   
 * @param clientConfiguration Client configuration for options such as proxy
 * settings, user-agent header, and network timeouts.
 */
public VeracodeAsyncClient(VeracodeCredentials credentials, ClientConfiguration clientConfiguration) {
    this.clientConfiguration = clientConfiguration;
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(TARGET), credentials);

    AuthCache authCache = new BasicAuthCache();
    authCache.put(TARGET, new BasicScheme());

    context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    try {
        client = HttpClientFactory.buildAsync(clientConfiguration);
    } catch (NoSuchAlgorithmException nsae) {
        throw new VeracodeClientException(nsae.getMessage(), nsae);
    }
}

From source file:org.apache.trafficcontrol.client.RestApiSession.java

public void open() {
    if (httpclient == null) {
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD) //User standard instead of default. Default will result in cookie parse exceptions with the Mojolicous cookie
                .setConnectTimeout(5000).build();
        CookieStore cookieStore = new BasicCookieStore();
        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookieStore);

        httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(globalConfig)
                .setDefaultCookieStore(cookieStore).build();
    }//  w w w.  ja  v a 2 s. c  om

    if (!httpclient.isRunning()) {
        httpclient.start();
    }
}

From source file:org.ops4j.pax.web.itest.FormAuthenticationTest.java

@Test
public void shouldDisplayProtectedPageAfterLogin() throws Exception {
    String path = String.format("http://localhost:%d/form/hello", getHttpPort());
    CloseableHttpClient client = HttpClients.createDefault();
    HttpClientContext context = HttpClientContext.create();

    HttpGet httpGet = new HttpGet(path);
    HttpResponse response = client.execute(httpGet, context);

    int statusCode = response.getStatusLine().getStatusCode();
    String text = EntityUtils.toString(response.getEntity());
    assertThat(text, containsString("Login"));

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("j_username", "mustermann"));
    formparams.add(new BasicNameValuePair("j_password", "mustermann"));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");

    path = String.format("http://localhost:%d/form/j_security_check", getHttpPort());
    HttpPost httpPost = new HttpPost(path);
    httpPost.setEntity(entity);/*from   w  w  w . j  av a  2s  . co m*/
    response = client.execute(httpPost, context);

    statusCode = response.getStatusLine().getStatusCode();
    assertThat(statusCode, is(302));
    String location = response.getFirstHeader("Location").getValue();
    assertThat(location, containsString("/form/hello"));

    httpGet = new HttpGet(location);
    response = client.execute(httpGet, context);

    statusCode = response.getStatusLine().getStatusCode();
    text = EntityUtils.toString(response.getEntity());
    assertThat(text, containsString("Hello from Pax Web!"));
}

From source file:com.cognifide.qa.bb.aem.core.login.AemAuthCookieFactoryImpl.java

/**
 * This method provides browser cookie for authenticating user to AEM instance
 *
 * @param url      URL to AEM instance, like http://localhost:4502
 * @param login    Username to use//from w ww  .  j av  a 2 s.c  om
 * @param password Password to use
 * @return Cookie for selenium WebDriver.
 */
@Override
public Cookie getCookie(String url, String login, String password) {
    if (!cookieJar.containsKey(url)) {
        HttpPost loginPost = new HttpPost(url + "/libs/granite/core/content/login.html/j_security_check");

        List<NameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("_charset_", "utf-8"));
        nameValuePairs.add(new BasicNameValuePair("j_username", login));
        nameValuePairs.add(new BasicNameValuePair("j_password", password));
        nameValuePairs.add(new BasicNameValuePair("j_validate", "true"));

        CookieStore cookieStore = new BasicCookieStore();
        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookieStore);

        try {
            loginPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            CloseableHttpResponse loginResponse = httpClient.execute(loginPost, context);
            loginResponse.close();
        } catch (IOException e) {
            LOG.error("Can't get AEM authentication cookie", e);
        } finally {
            loginPost.reset();
        }
        Cookie cookie = findAuthenticationCookie(cookieStore.getCookies());
        if (cookie != null) {
            cookieJar.put(url, cookie);
        }
    }
    return cookieJar.get(url);
}

From source file:fi.okm.mpass.shibboleth.monitor.AbstractSequenceStepResolverTest.java

@Test
public void testInitFailure() throws Exception {
    HttpClientBuilder clientBuilder = Mockito.mock(HttpClientBuilder.class);
    Mockito.when(clientBuilder.buildClient()).thenThrow(new Exception("mock"));
    resolver = new SearchKeyResolver("mock", clientBuilder);
    ((SearchKeyResolver) resolver).setId("mockId");
    boolean thrown = false;
    try {/*from  www . j  a v a 2  s .  co  m*/
        resolver.resolve(HttpClientContext.create(), new SequenceStep());
    } catch (Exception e) {
        thrown = true;
    }
    Assert.assertTrue(thrown);
}

From source file:com.sulacosoft.bitcoindconnector4j.BitcoindApiHandler.java

public BitcoindApiHandler(String host, int port, String protocol, String uri, String username,
        String password) {/*from w  w  w .j av a 2  s  . com*/
    this.uri = uri;

    httpClient = HttpClients.createDefault();
    targetHost = new HttpHost(host, port, protocol);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
}

From source file:org.wso2.carbon.apimgt.usage.client.DASRestClient.java

/**
 * Do a post request to the DAS REST//from  w  ww.j  a va 2s  . c o  m
 *
 * @param json lucene json request
 * @param url  DAS rest api location
 * @return return the HttpResponse after the request sent
 * @throws IOException throw if the connection exception occur
 */
CloseableHttpResponse post(String json, String url) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("Sending Lucene Query : " + json);
    }
    HttpPost postRequest = new HttpPost(url);
    HttpContext context = HttpClientContext.create();

    //get the encoded basic authentication
    String cred = RestClientUtil.encodeCredentials(this.user, this.pass);
    postRequest.addHeader(APIUsageStatisticsClientConstants.HTTP_AUTH_HEADER_NAME,
            APIUsageStatisticsClientConstants.HTTP_AUTH_HEADER_TYPE + ' ' + cred);
    StringEntity input = new StringEntity(json);
    input.setContentType(APIUsageStatisticsClientConstants.APPLICATION_JSON);
    postRequest.setEntity(input);

    //send the request
    return httpClient.execute(postRequest, context);
}

From source file:com.github.ljtfreitas.restify.http.client.request.apache.httpclient.ApacheHttpClientRequestFactory.java

public ApacheHttpClientRequestFactory(Charset charset) {
    this(HttpClients.createSystem(), null, HttpClientContext.create(), charset);
}

From source file:fr.treeptik.cloudunit.cli.rest.RestUtils.java

public Map<String, String> connect(String url, Map<String, Object> parameters) throws ManagerResponseException {

    Map<String, String> response = new HashMap<String, String>();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("j_username", (String) parameters.get("login")));
    nvps.add(new BasicNameValuePair("j_password", (String) parameters.get("password")));
    localContext = HttpClientContext.create();
    localContext.setCookieStore(new BasicCookieStore());
    HttpPost httpPost = new HttpPost(url);

    try {//from  www .java 2s.c om
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext);
        ResponseHandler<String> handler = new CustomResponseErrorHandler();
        String body = handler.handleResponse(httpResponse);
        response.put("body", body);
        httpResponse.close();
    } catch (Exception e) {
        authentificationUtils.getMap().clear();
        throw new ManagerResponseException(e.getMessage(), e);
    }

    return response;
}