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:fedroot.dacs.http.DacsClientContext.java

public DacsClientContext(HttpParams httpParams) {

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    if (httpParams.getParameter(ClientPNames.COOKIE_POLICY) == null) {
        httpParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    }/*from   w w w .  j  a v a 2s . c om*/
    httpClient = new DefaultHttpClient(cm, httpParams);

    cookieStore = new BasicCookieStore();
    httpContext = new BasicHttpContext();
    // Bind custom cookie store to the local context
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}

From source file:com.citrix.g2w.webdriver.util.FileDownloader.java

public String downloader(String fileToDownloadLocation, String localDownloadPath)
        throws IOException, URISyntaxException {
    URL fileToDownload = new URL(fileToDownloadLocation);
    String fileNameURI = fileToDownload.getFile();
    String filePath = "";
    if (fileNameURI.contains("?")) {
        filePath = localDownloadPath/*from  ww  w. ja va 2 s.c  om*/
                + fileNameURI.substring(fileNameURI.substring(0, fileNameURI.indexOf("?")).lastIndexOf("/") + 1,
                        fileNameURI.indexOf("?"));
    } else {
        filePath = localDownloadPath + fileNameURI.substring(fileNameURI.lastIndexOf("/") + 1);
    }
    File downloadedFile = new File(filePath);
    if (downloadedFile.canWrite() == false) {
        downloadedFile.setWritable(true);
    }

    HttpClient client = new DefaultHttpClient();
    BasicHttpContext localContext = new BasicHttpContext();

    if (this.mimicWebDriverCookieState) {
        localContext.setAttribute(ClientContext.COOKIE_STORE,
                this.mimicCookieState(this.driver.manage().getCookies()));
    }

    HttpGet httpget = new HttpGet(fileToDownload.toURI());
    HttpParams httpRequestParameters = httpget.getParams();
    httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, this.followRedirects);
    httpget.setParams(httpRequestParameters);

    HttpResponse response = client.execute(httpget, localContext);

    FileUtils.copyInputStreamToFile(response.getEntity().getContent(), downloadedFile);
    response.getEntity().getContent().close();

    String downloadedFileAbsolutePath = downloadedFile.getAbsolutePath();
    this.logger.log("File downloaded to '" + downloadedFileAbsolutePath + "'");

    return downloadedFileAbsolutePath;
}

From source file:org.mobicents.client.slee.resource.http.HttpClientResourceAdaptorSbbInterfaceImpl.java

@Override
public HttpClientActivity createHttpClientActivity(boolean endOnReceivingResponse, HttpContext context)
        throws StartActivityException {

    if (tracer.isFinestEnabled()) {
        tracer.finest("createHttpClientActivity(endOnReceivingResponse=" + endOnReceivingResponse + ",context="
                + context + ")");
    }/* w  w w  .j  ava  2s  . com*/

    if (!this.ra.isActive) {
        throw new IllegalStateException("ra is not in active state");
    }

    // Maintain HttpSession on server side
    if (context == null) {
        context = new BasicHttpContext();

    }
    if (context.getAttribute(ClientContext.COOKIE_STORE) == null) {
        BasicCookieStore cookieStore = new BasicCookieStore();
        context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    }

    HttpClientActivity activity = new HttpClientActivityImpl(this.ra, endOnReceivingResponse, context);

    HttpClientActivityHandle handle = new HttpClientActivityHandle(activity.getSessionId());

    // this happens with a tx context
    this.ra.getResourceAdaptorContext().getSleeEndpoint().startActivitySuspended(handle, activity,
            ACTIVITY_FLAGS);

    this.ra.addActivity(handle, activity);

    if (tracer.isFineEnabled()) {
        tracer.fine("Started activity " + activity.getSessionId() + ", context is " + context
                + ", endOnReceivingResponse is " + endOnReceivingResponse);
    }

    return activity;
}

From source file:com.lostad.app.base.util.RequestUtil.java

public static String postRequest(final String url, final StringEntity params, String token,
        final boolean isSingleton) throws Exception {
    String json = null;//from  w ww .  ja v  a 2  s .c o m
    HttpClient client = HttpClientManager.getHttpClient(isSingleton);
    HttpEntity resEntity = null;
    HttpPost post = new HttpPost(url);
    if (Validator.isNotEmpty(token)) {
        post.addHeader("token", token);
    }

    try {
        //long t1 = System.currentTimeMillis();

        if (params != null) {
            params.setContentEncoding(HTTP.UTF_8);
            params.setContentType("application/x-www-form-urlencoded");
            post.setEntity(params);
        }

        HttpResponse response = client.execute(post, new BasicHttpContext());
        resEntity = response.getEntity();
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 200
            //?
            json = EntityUtils.toString(resEntity);
        }
    } catch (Exception e) {
        if (post != null) {
            post.abort();
        }
        throw e;
    } finally {

        if (resEntity != null) {
            try {
                resEntity.consumeContent();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        client.getConnectionManager().closeExpiredConnections();
    }
    return json;
}

From source file:com.socrata.ApiBase.java

private void finishConstruction() {
    // Store these because we need them for some specialized calls
    this.username = properties.getString("username");
    this.password = properties.getString("password");
    this.appToken = properties.getString("app_token");

    batchQueue = new ArrayList<BatchRequest>();

    setupBasicAuthentication();/*w w w . j a va  2  s. c om*/

    httpHost = new HttpHost(properties.getString("hostname"),
            Integer.valueOf(properties.getString("hostport")));

    httpContext = new BasicHttpContext();
}

From source file:com.wareninja.opensource.dizlink.utils.MyWebClient.java

protected void initBase() {
    httpClient = HttpClients.createDefault();
    httpRequestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).build();

    localContext = new BasicHttpContext();
}

From source file:com.janoz.usenet.processors.impl.WebbasedProcessor.java

public WebbasedProcessor() {
    BasicHttpParams params = new BasicHttpParams();
    params.setParameter(CookieSpecPNames.DATE_PATTERNS,
            Arrays.asList("EEE, dd-MMM-yyyy HH:mm:ss z", "EEE, dd MMM yyyy HH:mm:ss z"));
    httpClient = new DefaultHttpClient(params);
    cookieStore = new BasicCookieStore();
    context = new BasicHttpContext();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}

From source file:org.apache.geode.tools.pulse.PulseVerificationTest.java

@Before
public void before() throws Exception {
    httpClient = HttpClients.createDefault();
    context = new BasicHttpContext();
}

From source file:org.jboss.as.test.integration.management.console.XFrameOptionsHeaderTestCase.java

private void checkURLForHeader(URL url, String headerName, String expectedHeaderValue)
        throws URISyntaxException, IOException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(createCredentialsProvider(url)).build()) {
        HttpContext httpContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet(url.toURI());
        HttpResponse response = httpClient.execute(httpGet, httpContext);

        int statusCode = response.getStatusLine().getStatusCode();
        assertEquals("Wrong response code: " + statusCode + " for url '" + url.toString() + "'.",
                HttpURLConnection.HTTP_OK, statusCode);

        Header[] headers = response.getHeaders(headerName);
        assertNotNull("Unexpected behaviour of HttpResponse#getHeaders() returned null!", headers);
        assertTrue("There is no '" + headerName + "' header present! Headers present: "
                + Arrays.toString(response.getAllHeaders()), headers.length > 0);
        for (Header header : headers) {
            if (header.getValue().equals(expectedHeaderValue)) {
                return;
            }// ww  w.  jav a2s  . c  o m
        }
        fail("No header '" + headerName + "' with value '" + expectedHeaderValue + "' found!");
    }
}

From source file:com.aspire.mandou.framework.http.BetterHttpRequestBase.java

@Override
public BetterHttpResponse send() throws ConnectException {

    BetterHttpRequestRetryHandler retryHandler = new BetterHttpRequestRetryHandler(maxRetries);

    // tell HttpClient to user our own retry handler
    httpClient.setHttpRequestRetryHandler(retryHandler);

    HttpContext context = new BasicHttpContext();

    // Grab a coffee now and lean back, I'm not good at explaining stuff. This code realizes
    // a second retry layer on top of HttpClient. Rationale: HttpClient.execute sometimes craps
    // out even *before* the HttpRequestRetryHandler set above is called, e.g. on a
    // "Network unreachable" SocketException, which can happen when failing over from Wi-Fi to
    // 3G or vice versa. Hence, we catch these exceptions, feed it through the same retry
    // decision method *again*, and align the execution count along the way.
    boolean retry = true;
    IOException cause = null;//from w w w  . java2 s.co  m
    while (retry) {
        try {
            return httpClient.execute(request, this, context);
        } catch (IOException e) {
            cause = e;
            retry = retryRequest(retryHandler, cause, context);
        } catch (NullPointerException e) {
            // there's a bug in HttpClient 4.0.x that on some occasions causes
            // DefaultRequestExecutor to throw an NPE, see
            // http://code.google.com/p/android/issues/detail?id=5255
            cause = new IOException("NPE in HttpClient" + e.getMessage());
            retry = retryRequest(retryHandler, cause, context);
        } finally {
            // if timeout was changed with this request using withTimeout(), reset it
            if (oldTimeout != BetterHttp.getSocketTimeout()) {
                BetterHttp.setSocketTimeout(oldTimeout);
            }
        }
    }

    // no retries left, crap out with exception
    ConnectException ex = new ConnectException();
    ex.initCause(cause);
    throw ex;
}