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.eviware.soapui.support.httpclient.JCIFSTest.java

@Test
public void test() throws ParseException, IOException {
    try {//from  ww w.j  a v  a2s  . c om
        DefaultHttpClient httpClient = new DefaultHttpClient();

        httpClient.getAuthSchemes().register(AuthPolicy.NTLM, new NTLMSchemeFactory());
        httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, new NTLMSchemeFactory());

        NTCredentials creds = new NTCredentials("testuser", "kebabsalladT357", "", "");
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

        HttpHost target = new HttpHost("dev-appsrv01.eviware.local", 81, "http");
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpget = new HttpGet("/");

        HttpResponse response1 = httpClient.execute(target, httpget, localContext);
        HttpEntity entity1 = response1.getEntity();

        //      System.out.println( "----------------------------------------" );
        //System.out.println( response1.getStatusLine() );
        //      System.out.println( "----------------------------------------" );
        if (entity1 != null) {
            //System.out.println( EntityUtils.toString( entity1 ) );
        }
        //      System.out.println( "----------------------------------------" );

        // This ensures the connection gets released back to the manager
        EntityUtils.consume(entity1);

        Assert.assertEquals(response1.getStatusLine().getStatusCode(), 200);
    } catch (UnknownHostException e) {
        /* ignore */
    } catch (HttpHostConnectException e) {
        /* ignore */
    } catch (SocketException e) {
        /* ignore */
    }

    Assert.assertTrue(true);
}

From source file:com.basistech.readability.HttpPageReader.java

/** {@inheritDoc}*/
@Override/*from w  w w . j a v a 2  s. 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:com.intel.iotkitlib.LibHttp.HttpDeleteTask.java

private CloudResponse doWork(HttpClient httpClient, String url) {
    try {/*  www . ja v  a 2s  .  c om*/
        HttpContext localContext = new BasicHttpContext();
        HttpDelete httpDelete = new HttpDelete(url);
        //adding headers one by one
        for (NameValuePair nvp : headerList) {
            httpDelete.addHeader(nvp.getName(), nvp.getValue());
        }
        if (debug) {
            Log.e(TAG, "URI is : " + httpDelete.getURI());
            Header[] headers = httpDelete.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Log.e(TAG, "Header " + i + " is :" + headers[i].getName() + ":" + headers[i].getValue());
            }
        }
        HttpResponse response = httpClient.execute(httpDelete, localContext);
        if (response != null && response.getStatusLine() != null) {
            if (debug)
                Log.d(TAG, "response: " + response.getStatusLine().getStatusCode());
        }
        HttpEntity responseEntity = response != null ? response.getEntity() : null;
        StringBuilder builder = new StringBuilder();
        if (responseEntity != null) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(responseEntity.getContent(), HTTP.UTF_8));
            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }
            if (debug)
                Log.d(TAG, "Response received is :" + builder.toString());
        }
        CloudResponse cloudResponse = new CloudResponse();
        if (response != null) {
            cloudResponse.code = response.getStatusLine().getStatusCode();
        }
        cloudResponse.response = builder.toString();
        return cloudResponse;
    } catch (java.net.ConnectException cEx) {
        Log.e(TAG, cEx.getMessage());
        return null;
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return null;
    }
}

From source file:org.openexchangerates.OpenExchangeRatesClient.java

/**
 * Get the latest exchange rates/*from ww  w . ja  v  a2 s.c  om*/
 *
 * @return Last updated exchange rates
 */
public Map<Currency, BigDecimal> getLatest() throws UnavailableExchangeRateException {

    String url = String.format(OER_URL, mAppKey);

    HttpGet get = new HttpGet(url);

    // Execute the request
    HttpContext context = new BasicHttpContext();
    HttpResponse response;
    try {
        response = ConnectionManager.getHttpClient().execute(get, context);
    } catch (IOException e) {
        throw new UnavailableExchangeRateException(e);
    }

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new UnavailableExchangeRateException("Could not fetch data");
    }

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
        OERResult result = mGson.fromJson(reader, OERResult.class);
        return result.rates;
    } catch (Exception e) {
        throw new UnavailableExchangeRateException(e);
    }
}

From source file:com.intel.iotkitlib.LibHttp.HttpGetTask.java

private CloudResponse doWork(HttpClient httpClient, String url) {
    try {/*from www  .jav  a2s . co m*/
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet(url);
        //adding headers one by one
        for (NameValuePair nvp : headerList) {
            httpGet.addHeader(nvp.getName(), nvp.getValue());
        }
        if (debug) {
            Log.e(TAG, "URI is : " + httpGet.getURI());
            Header[] headers = httpGet.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Log.e(TAG, "Header " + i + " is :" + headers[i].getName() + ":" + headers[i].getValue());
            }
        }
        HttpResponse response = httpClient.execute(httpGet, localContext);
        if (response != null && response.getStatusLine() != null) {
            if (debug)
                Log.d(TAG, "response: " + response.getStatusLine().getStatusCode());
        }

        HttpEntity responseEntity = response != null ? response.getEntity() : null;
        StringBuilder builder = new StringBuilder();
        if (responseEntity != null) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(responseEntity.getContent(), HTTP.UTF_8));
            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }
            if (debug)
                Log.d(TAG, "Response received is :" + builder.toString());
        }

        CloudResponse cloudResponse = new CloudResponse();
        if (response != null) {
            cloudResponse.code = response.getStatusLine().getStatusCode();
        }
        cloudResponse.response = builder.toString();
        return cloudResponse;
    } catch (java.net.ConnectException cEx) {
        Log.e(TAG, cEx.getMessage());
        return null;
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return null;
    }
}

From source file:de.chaosdorf.meteroid.longrunningio.LongRunningIOGet.java

@Override
protected String doInBackground(Void... params) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(url);
    try {/*from   www .  j  ava 2  s  . co  m*/
        HttpResponse response = httpClient.execute(httpGet, localContext);
        int code = response.getStatusLine().getStatusCode();
        if (code >= 400 && code <= 599) {
            callback.displayErrorMessage(id, response.getStatusLine().getReasonPhrase());
            return null;
        }
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity, HTTP.UTF_8);
    } catch (Exception e) {
        callback.displayErrorMessage(id, e.getLocalizedMessage());
        return null;
    }
}

From source file:lets.code.project.conectividad.BasicWebService.java

public BasicWebService(String serviceName) {
    HttpParams myParams = new BasicHttpParams();

    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
    HttpConnectionParams.setSoTimeout(myParams, 10000);
    httpClient = new DefaultHttpClient(myParams);
    localContext = new BasicHttpContext();
    webServiceUrl = serviceName;//  w  w  w.ja va2s . co m

}

From source file:org.bishoph.oxdemo.util.OXLoginAction.java

public OXLoginAction(OXDemo oxdemo) {
    this.oxdemo = oxdemo;
    if (httpclient == null) {
        CookieStore cookieStore = new BasicCookieStore();
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        httpclient = new DefaultHttpClient(params);
        localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    }/*from w w  w .ja va 2  s .com*/
}

From source file:org.wso2.developerstudio.appfactory.core.client.RssClient.java

public static String getDBinfo(String operation, String dsBaseUrl) {
    String url = dsBaseUrl + "NDataSourceAdmin";
    DefaultHttpClient client = new DefaultHttpClient();
    client = (DefaultHttpClient) HttpsJaggeryClient.wrapClient(client, url);
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(Authenticator.getInstance().getCredentials().getUser(),
                    Authenticator.getInstance().getCredentials().getPassword()));

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

    HttpPost post = new HttpPost(url);
    String sopactionValue = "urn:" + operation;
    post.addHeader("SOAPAction", sopactionValue);
    String body = createPayLoad(operation);
    try {// ww  w  . j  av  a2 s  . c  om
        StringEntity entity = new StringEntity(body.toString(), "text/xml", HTTP.DEFAULT_CONTENT_CHARSET);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        if (200 == response.getStatusLine().getStatusCode()) {
            HttpEntity entityGetAppsOfUser = response.getEntity();
            BufferedReader rd = new BufferedReader(new InputStreamReader(entityGetAppsOfUser.getContent()));
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            String respond = sb.toString();
            EntityUtils.consume(entityGetAppsOfUser);
            return respond;
        }
    } catch (Exception e) {
        // log.error("Jenkins Client err", e);
    }
    return null;
}

From source file:org.sonatype.nexus.httpclient.internal.NexusRedirectStrategyTest.java

@Test
public void doNotFollowRedirectsToDirIndex() throws Exception {
    when(response.getStatusLine()).thenReturn(statusLine);

    final RedirectStrategy underTest = new NexusRedirectStrategy();
    HttpContext httpContext;/* ww w  . j  ava2 s .  c o  m*/

    // no location header
    request = new HttpGet("http://localhost/dir/fileA");
    httpContext = new BasicHttpContext();
    httpContext.setAttribute(CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE);
    when(statusLine.getStatusCode()).thenReturn(SC_OK);
    assertThat(underTest.isRedirected(request, response, httpContext), is(false));

    // redirect to file
    request = new HttpGet("http://localhost/dir/fileA");
    httpContext = new BasicHttpContext();
    httpContext.setAttribute(CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE);
    when(statusLine.getStatusCode()).thenReturn(SC_MOVED_TEMPORARILY);
    when(response.getFirstHeader(argThat(equalToIgnoringCase(LOCATION))))
            .thenReturn(new BasicHeader(LOCATION, "http://localhost/dir/fileB"));
    assertThat(underTest.isRedirected(request, response, httpContext), is(true));

    // redirect to dir
    request = new HttpGet("http://localhost/dir");
    httpContext = new BasicHttpContext();
    httpContext.setAttribute(CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE);
    when(statusLine.getStatusCode()).thenReturn(SC_MOVED_TEMPORARILY);
    when(response.getFirstHeader(argThat(equalToIgnoringCase(LOCATION))))
            .thenReturn(new BasicHeader(LOCATION, "http://localhost/dir/"));
    assertThat(underTest.isRedirected(request, response, httpContext), is(false));
}