Example usage for org.apache.http.protocol BasicHttpContext BasicHttpContext

List of usage examples for org.apache.http.protocol BasicHttpContext BasicHttpContext

Introduction

In this page you can find the example usage for org.apache.http.protocol BasicHttpContext BasicHttpContext.

Prototype

public BasicHttpContext() 

Source Link

Usage

From source file:com.google.cloud.trace.apachehttp.TraceRequestInterceptorTest.java

@Test
public void testProcess() throws Exception {
    HttpContext context = new BasicHttpContext();
    requestInterceptor.process(requestWithHeaders, context);
    assertThat(context.getAttribute("TRACE-CONTEXT")).isEqualTo(testContext);

    ArgumentCaptor<HttpRequest> captor = ArgumentCaptor.forClass(HttpRequest.class);
    verify(mockDelegate).process(captor.capture());
    HttpRequest request = captor.getValue();
    assertThat(request.getMethod()).isEqualTo("GET");
    assertThat(request.getProtocol()).isEqualTo("HTTP");
    assertThat(request.getURI()).isEqualTo(URI.create("http://example.com/foo/bar"));
    assertThat(request.getHeader("User-Agent")).isEqualTo("test-user-agent");
}

From source file:org.eclipse.lyo.rio.trs.tests.ChangeLogUpdationTest.java

@BeforeClass
public static void setupOnce() {
    try {//from w ww  .  j  a va  2s  . c  o m
        prop = getConfigPropertiesInstance();
        String resCreationFactoryUri = prop.getProperty("configResourceCreationFactoryUri");
        String resCreationContent = (prop.getProperty("configResContentFile").equals("")
                ? prop.getProperty("configResContent")
                : readFileAsString(new File(RESOURCES + FileSep + prop.getProperty("configResContentFile"))));
        String resContentType = prop.getProperty("configContentType");
        String resUpdateContentType = prop.getProperty("configUpdateContentType");
        String trsEndpoint = prop.getProperty("configTrsEndpoint");
        String acceptType = prop.getProperty("acceptType");

        httpClient = new EasySSLClient().getClient();
        httpContext = new DefaultedHttpContext(new BasicHttpContext(), new SyncBasicHttpContext(null));

        //Create a resource using the resource creation factory.. oslc:CreationFactory
        createdResourceUrl = SendUtil.createResource(resCreationFactoryUri, httpClient, httpContext,
                resContentType, resCreationContent);

        //Now Update the resource using a HTTP PUT call
        String updateContent = readFileAsString(
                new File(RESOURCES + FileSep + prop.getProperty("configResUpdateFile")));

        //Replace the Update content with the correct resource identifier of the resource created above
        updateContent = formatUpdateContent(updateContent, resUpdateContentType);

        SendUtil.updateResource(createdResourceUrl, httpClient, httpContext, resUpdateContentType,
                updateContent);

        trsResource = getResource(trsEndpoint, httpClient, httpContext, acceptType);

    } catch (FileNotFoundException e) {
        terminateTest(Messages.getServerString("tests.general.config.properties.missing"), e);
    } catch (IOException e) {
        terminateTest(Messages.getServerString("tests.general.config.properties.unreadable"), e);
    } catch (FetchException e) {
        terminateTest(Messages.getServerString("tests.general.trs.fetch.error"), e);
    } catch (SendException e) {
        terminateTest(Messages.getServerString("tests.general.trs.send.error"), e);
    } catch (Exception e) {
        terminateTest(null, e);
    }
}

From source file:org.cerberus.util.HTTPSession.java

/**
 * Start a HTTP Session with authorisation
 *
 * @param username//  w  w w . j a  va2  s.  c  o m
 * @param password
 */
public void startSession(String username, String password) {
    // Create your httpclient
    client = new DefaultHttpClient();
    client.getParams().setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    // Then provide the right credentials
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));

    // Generate BASIC scheme object and stick it to the execution context
    basicAuth = new BasicScheme();
    context = new BasicHttpContext();
    context.setAttribute("preemptive-auth", basicAuth);

    // Add as the first (because of the zero) request interceptor
    // It will first intercept the request and preemptively initialize the authentication scheme if there is not
    client.addRequestInterceptor(new PreemptiveAuth(), 0);
}

From source file:RestApiHttpClient.java

/**
 * Create an new {@link RestApiHttpClient} instance with Endpoint, username and API-Key
 * /*  w  w w  .j av a  2 s  . co  m*/
 * @param apiEndpoint The Hostname and Api-Endpoint (http://www.example.com/api)
 * @param username Shopware Username
 * @param password Api-Key from User-Administration
 */
public RestApiHttpClient(URL apiEndpoint, String username, String password) {
    this.apiEndpoint = apiEndpoint;

    BasicHttpContext context = new BasicHttpContext();
    this.localContext = HttpClientContext.adapt(context);
    HttpHost target = new HttpHost(this.apiEndpoint.getHost(), -1, this.apiEndpoint.getProtocol());
    this.localContext.setTargetHost(target);

    TargetAuthenticationStrategy authStrat = new TargetAuthenticationStrategy();
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    AuthScope aScope = new AuthScope(target.getHostName(), target.getPort());
    credsProvider.setCredentials(aScope, creds);

    BasicAuthCache authCache = new BasicAuthCache();
    // Digest Authentication
    DigestScheme digestAuth = new DigestScheme(Charset.forName("UTF-8"));
    authCache.put(target, digestAuth);
    this.localContext.setAuthCache(authCache);
    this.localContext.setCredentialsProvider(credsProvider);

    ArrayList<Header> defHeaders = new ArrayList<>();
    defHeaders.add(new BasicHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()));
    this.httpclient = HttpClients.custom().useSystemProperties().setTargetAuthenticationStrategy(authStrat)
            .disableRedirectHandling()
            // make Rest-API Endpoint GZIP-Compression enable comment this out
            // Response-Compression is also possible
            .disableContentCompression().setDefaultHeaders(defHeaders)
            .setDefaultCredentialsProvider(credsProvider).build();

}

From source file:de.jetwick.snacktory.HijackableHttpPageReader.java

/** {@inheritDoc}*/
@SuppressWarnings("deprecation")
@Override/*from  w w w. j  av  a2 s  . c  o  m*/
public String readPage(String url) throws PageReadException {
    if (url.equals(this.url) && StringUtils.isNotEmpty(pageHtml)) {
        LOG.info("Use already fetched content of " + url);

        return pageHtml;
    } else {
        LOG.info("Reading " + url);
        this.url = url;
        this.pageHtml = null;

        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT) 
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 10000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);

        HttpContext localContext = new BasicHttpContext();
        HttpGet get = new HttpGet(url);
        get.setHeader("User-Agent", userAgent);
        InputStream response = null;
        HttpResponse httpResponse = null;
        try {
            try {
                httpResponse = httpclient.execute(get, localContext);
                int resp = httpResponse.getStatusLine().getStatusCode();
                if (HttpStatus.SC_OK != resp) {
                    LOG.error("Download failed of " + url + " status " + resp + " "
                            + httpResponse.getStatusLine().getReasonPhrase());
                    return null;
                }
                String respCharset = EntityUtils.getContentCharSet(httpResponse.getEntity());

                pageHtml = readContent(httpResponse.getEntity().getContent(), respCharset);
                return pageHtml;
            } finally {
                if (response != null) {
                    response.close();
                }
                if (httpResponse != null && httpResponse.getEntity() != null) {
                    httpResponse.getEntity().consumeContent();
                }

            }
        } catch (IOException e) {
            LOG.error("Download failed of " + url, e);
            throw new PageReadException("Failed to read " + url, e);
        }
    }
}

From source file:de.jetwick.snacktory.HttpPageReader.java

/** {@inheritDoc}*/
@SuppressWarnings("deprecation")
@Override//www.j ava 2s .  c om
public String readPage(String url) throws PageReadException {
    LOG.info("Reading " + url);
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 10000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpContext localContext = new BasicHttpContext();
    HttpGet get = new HttpGet(url);
    InputStream response = null;
    HttpResponse httpResponse = null;
    try {
        try {
            httpResponse = httpclient.execute(get, localContext);
            int resp = httpResponse.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK != resp) {
                LOG.error("Download failed of " + url + " status " + resp + " "
                        + httpResponse.getStatusLine().getReasonPhrase());
                return null;
            }
            String respCharset = EntityUtils.getContentCharSet(httpResponse.getEntity());

            return readContent(httpResponse.getEntity().getContent(), respCharset);
        } finally {
            if (response != null) {
                response.close();
            }
            if (httpResponse != null && httpResponse.getEntity() != null) {
                httpResponse.getEntity().consumeContent();
            }

        }
    } catch (IOException e) {
        LOG.error("Download failed of " + url, e);
        throw new PageReadException("Failed to read " + url, e);
    }
}

From source file:org.jboss.as.test.integration.management.http.XCorrelationIdTestCase.java

@Before
public void before() throws Exception {

    this.url = new URL("http", managementClient.getMgmtAddress(), MGMT_PORT, MGMT_CTX);
    this.httpContext = new BasicHttpContext();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(Authentication.USERNAME, Authentication.PASSWORD));

    this.httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
}

From source file:com.entertailion.android.dial.HttpRequestHelper.java

public HttpRequestHelper() {
    httpClient = createHttpClient();
    localContext = new BasicHttpContext();
}

From source file:com.wondershare.http.core.Dispatcher.java

@Override
public void run() {
    DefaultHttpServerConnection httpServerConnnection = null;
    try {/*from ww w .  ja  v a2s . c o m*/
        httpServerConnnection = new DefaultHttpServerConnection();
        httpServerConnnection.bind(socket, new BasicHttpParams());
        // ??
        TResponse response = TResponse.getInstance();
        response.setContext(mContext);
        httpService.setHandlerResolver(response.getHttpRequestHandler());

        // 
        httpService.handleRequest(httpServerConnnection, new BasicHttpContext());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (HttpException e) {
        e.printStackTrace();
    } finally {
        try {
            if (httpServerConnnection != null) {
                httpServerConnnection.shutdown();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.subgraph.vega.internal.http.requests.HttpRequestEngine.java

@Override
public IHttpResponse sendRequest(HttpUriRequest request, HttpContext context) throws RequestEngineException {
    final HttpContext requestContext = (context == null) ? (new BasicHttpContext()) : (context);
    requestContext.setAttribute(ClientContext.COOKIE_STORE, config.getCookieStore());
    Future<IHttpResponse> future = executor
            .submit(new RequestTask(client, rateLimit, request, requestContext, config, htmlParser));
    try {//from  w  w  w . jav a 2 s.  co  m
        return future.get();
    } catch (InterruptedException e) {
        logger.info("Request " + request.getURI() + " was interrupted before completion");
    } catch (ExecutionException e) {
        throw translateException(request, e.getCause());
    }
    return null;
}