Example usage for org.apache.http.impl.client DefaultHttpClient addRequestInterceptor

List of usage examples for org.apache.http.impl.client DefaultHttpClient addRequestInterceptor

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient addRequestInterceptor.

Prototype

public synchronized void addRequestInterceptor(final HttpRequestInterceptor itcp, final int index) 

Source Link

Usage

From source file:com.deliciousdroid.client.DeliciousApi.java

/**
 * Performs an api call to Delicious's http based api methods.
 * /*from  w  w  w .  jav a2 s  .c  o m*/
 * @param url URL of the api method to call.
 * @param params Extra parameters included in the api call, as specified by different methods.
 * @param account The account being synced.
 * @param context The current application context.
 * @return A String containing the response from the server.
 * @throws IOException If a server error was encountered.
 * @throws AuthenticationException If an authentication error was encountered.
 */
private static InputStream DeliciousApiCall(String url, TreeMap<String, String> params, Account account,
        Context context) throws IOException, AuthenticationException {

    final AccountManager am = AccountManager.get(context);

    if (account == null)
        throw new AuthenticationException();

    final String username = account.name;
    String authtoken = null;

    try {
        authtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, false);
    } catch (OperationCanceledException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (AuthenticatorException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Uri.Builder builder = new Uri.Builder();
    builder.scheme(SCHEME);
    builder.authority(DELICIOUS_AUTHORITY);
    builder.appendEncodedPath(url);
    for (String key : params.keySet()) {
        builder.appendQueryParameter(key, params.get(key));
    }

    String apiCallUrl = builder.build().toString();

    Log.d("apiCallUrl", apiCallUrl);
    final HttpGet post = new HttpGet(apiCallUrl);

    post.setHeader("User-Agent", "DeliciousDroid");
    post.setHeader("Accept-Encoding", "gzip");

    DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient();
    CredentialsProvider provider = client.getCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials(username, authtoken);
    provider.setCredentials(SCOPE, credentials);

    client.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);

    final HttpResponse resp = client.execute(post);

    final int statusCode = resp.getStatusLine().getStatusCode();

    if (statusCode == HttpStatus.SC_OK) {

        final HttpEntity entity = resp.getEntity();

        InputStream instream = entity.getContent();

        final Header encoding = entity.getContentEncoding();

        if (encoding != null && encoding.getValue().equalsIgnoreCase("gzip")) {
            instream = new GZIPInputStream(instream);
        }

        return instream;
    } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        throw new AuthenticationException();
    } else {
        throw new IOException();
    }
}

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

public static HttpResponse getBulildinfo(String applicationId, String version, String builderBaseUrl,
        int lastBuildNo) {

    DefaultHttpClient client = new DefaultHttpClient();
    client = (DefaultHttpClient) HttpsJaggeryClient.wrapClient(client, builderBaseUrl);
    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);

    // 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);
    String getUrl = builderBaseUrl + "/job/" + applicationId + "-" + version + "-default/" + lastBuildNo
            + "/consoleText";
    HttpGet get = new HttpGet(getUrl);

    try {/*from w ww  .j  a  v a  2  s .  c  om*/
        // Execute your request with the given context
        HttpResponse response = client.execute(get, context);
        return response;
    } catch (Exception e) {
        log.error("Jenkins Client err", e);
    }
    return null;
}

From source file:org.n52.oxf.util.web.BasicAuthenticationHttpClient.java

private void addAuthenticationInterceptor(DefaultHttpClient httpclient) {
    httpclient.addRequestInterceptor(getAuthenticationIntercepter(), 0);
}

From source file:org.cogsurv.cogsurver.http.HttpApiWithBasicAuth.java

public HttpApiWithBasicAuth(DefaultHttpClient httpClient, String clientVersion) {
    super(httpClient, clientVersion);
    httpClient.addRequestInterceptor(preemptiveAuth, 0);
}

From source file:com.suse.studio.api.lib.HttpClient.java

private DefaultHttpClient getHttpClient(final String userName, final String apiKey) {
    HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            if (authState.getAuthScheme() == null) {
                authState.setAuthScheme(new BasicScheme());
                authState.setCredentials(new UsernamePasswordCredentials(userName, apiKey));
            }//from   w ww .  j a v a 2  s .  c o m
        }
    };
    DefaultHttpClient client = new DefaultHttpClient();
    client.addRequestInterceptor(preemptiveAuth, 0);
    return client;
}

From source file:com.cloudhopper.httpclient.util.HttpSender.java

static public Response postXml(String url, String username, String password, String requestXml)
        throws Exception {
    ////from  w  ww . j a  v a 2 s  . c o m
    // trust any SSL connection
    //
    TrustManager easyTrustManager = new X509TrustManager() {
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", sf, 443);

    //SchemeRegistry sr = new SchemeRegistry();
    //sr.register(http);
    //sr.register(https);

    // create and initialize scheme registry
    //SchemeRegistry schemeRegistry = new SchemeRegistry();
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    //ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    //cm.setMaxTotalConnections(1);

    DefaultHttpClient client = new DefaultHttpClient();

    client.getConnectionManager().getSchemeRegistry().register(https);

    HttpPost post = new HttpPost(url);

    StringEntity postEntity = new StringEntity(requestXml, "ISO-8859-1");
    postEntity.setContentType("text/xml; charset=\"ISO-8859-1\"");
    post.addHeader("SOAPAction", "\"\"");
    post.setEntity(postEntity);

    long start = System.currentTimeMillis();

    client.getCredentialsProvider().setCredentials(new AuthScope(null, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));

    BasicHttpContext localcontext = new BasicHttpContext();

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

    // Add as the first request interceptor
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpResponse httpResponse = client.execute(post, localcontext);
    HttpEntity responseEntity = httpResponse.getEntity();

    Response rsp = new Response();

    // set the status line and reason
    rsp.statusCode = httpResponse.getStatusLine().getStatusCode();
    rsp.statusLine = httpResponse.getStatusLine().getReasonPhrase();

    // get an input stream
    rsp.body = EntityUtils.toString(responseEntity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    client.getConnectionManager().shutdown();

    return rsp;
}

From source file:com.ibm.sbt.services.client.CookieStoreClientService.java

@Override
protected void initialize(DefaultHttpClient httpClient) throws ClientServicesException {
    super.initialize(httpClient);

    httpClient.addRequestInterceptor(new CookieInterceptor(), 1);
}

From source file:com.liferay.portal.search.solr.http.BasePoolingHttpClientFactory.java

protected void applyProperties(DefaultHttpClient defaultHttpClient) {
    for (HttpRequestInterceptor httpRequestInterceptor : _httpRequestInterceptors) {

        defaultHttpClient.addRequestInterceptor(httpRequestInterceptor, 0);
    }/*from w  w  w .  j a  va 2  s.  com*/
}

From source file:com.predic8.membrane.test.AssertUtils.java

private static DefaultHttpClient getAuthenticatingHttpClient(String host, int port, String user, String pass) {
    DefaultHttpClient hc = new DefaultHttpClient();
    HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.update(new BasicScheme(), creds);
                }/*from  w w w.j  av a 2s.  c  o m*/
            }
        }
    };
    hc.addRequestInterceptor(preemptiveAuth, 0);
    Credentials defaultcreds = new UsernamePasswordCredentials(user, pass);
    BasicCredentialsProvider bcp = new BasicCredentialsProvider();
    bcp.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds);
    hc.setCredentialsProvider(bcp);
    hc.setCookieStore(new BasicCookieStore());
    return hc;
}

From source file:se.vgregion.pubsub.twitter.impl.TwitterStreamConsumer.java

private void consume() throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.addRequestInterceptor(new PreemptiveBasicAuth(username, password), 0);

    // reconnect directly on normal disconnects
    while (!stopped) {
        HttpUriRequest request;//from  w w  w .  jav a  2s .  co m
        if (url.toString().startsWith(TwitterPublisher.FILTER_URL)) {
            String filter = url.getFragment();

            HttpPost post = new HttpPost(TwitterPublisher.FILTER_URL);
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
                    Arrays.asList(new BasicNameValuePair("track", filter)));
            post.setEntity(entity);

            request = post;
        } else {
            request = new HttpGet(TwitterPublisher.SAMPLE_URL);
        }
        HttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new IOException("HTTP failure: " + response.getStatusLine());
        }

        HttpEntity responseEntity = response.getEntity();
        BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));

        ObjectMapper mapper = new ObjectMapper();

        String line = reader.readLine();
        while (line != null && !stopped) {
            JsonNode tweet = mapper.readValue(line, JsonNode.class);

            EntryBuilder entryBuilder = new EntryBuilder().id(valueAsString(tweet.get("id_str")));
            entryBuilder.field(new JsonNodeField("tweet", tweet));

            Feed feed = new FeedBuilder(ContentType.JSON).id(url.toString()).entry(entryBuilder.build())
                    .build();

            pubSubEngine.publish(url, feed);
            line = reader.readLine();
        }

        if (stopped) {
            // try to shut down nicely
            responseEntity.consumeContent();
        }
    }
}