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:org.apache.solr.client.solrj.impl.PreemptiveBasicAuthConfigurer.java

@Override
public void configure(DefaultHttpClient httpClient, SolrParams config) {
    config = SolrParams.wrapDefaults(config, defaultParams);
    final String basicAuthUser = config.get(HttpClientUtil.PROP_BASIC_AUTH_USER);
    final String basicAuthPass = config.get(HttpClientUtil.PROP_BASIC_AUTH_PASS);
    if (basicAuthUser == null || basicAuthPass == null) {
        throw new IllegalArgumentException(
                "username & password must be specified with " + getClass().getName());
    }/*from  w  w  w . j  a va2  s. co m*/
    super.configure(httpClient, config);
    httpClient.addRequestInterceptor(new PreemptiveAuth(new BasicScheme()), 0);
}

From source file:net.homelinux.penecoptero.android.citybikes.app.RESTHelper.java

private DefaultHttpClient setCredentials(DefaultHttpClient httpclient, String url)
        throws HttpException, IOException {
    HttpHost targetHost = new HttpHost(url);
    final UsernamePasswordCredentials access = new UsernamePasswordCredentials(USERNAME, PASSWORD);

    httpclient.getCredentialsProvider()//from   ww w . j  av  a 2 s .co  m
            .setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), access);

    httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {

            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            if (authState.getAuthScheme() == null) {
                authState.setAuthScheme(new BasicScheme());
                authState.setCredentials(access);
            }
        }
    }, 0);
    return httpclient;
}

From source file:com.ibm.sbt.services.endpoints.BasicEndpoint.java

@Override
public void initialize(DefaultHttpClient httpClient) throws ClientServicesException {
    String usr = getUserIdentity();
    if (StringUtil.isNotEmpty(usr)) {
        String pwd = getPassword();

        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(usr, pwd);

        HttpRequestInterceptor basicInterceptor = new BasicInterceptor(creds);
        httpClient.addRequestInterceptor(basicInterceptor, 0);
    }/*  ww w .ja va 2 s. c om*/
}

From source file:pl.llp.aircasting.util.http.HttpBuilder.java

private <T> HttpResult<T> doRequest(HttpUriRequest request, Type target) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResult<T> result = new HttpResult<T>();
    Reader reader = null;//from   w w  w .j  a va  2s  . c  om
    InputStream content = null;

    // scoped so high for debugging connectivity in devMode
    String fullJson = null;
    try {
        client.addRequestInterceptor(preemptiveAuth(), 0);

        HttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 204) {
            result.setStatus(Status.SUCCESS);
            return result;
        }

        content = response.getEntity().getContent();

        reader = new InputStreamReader(content);

        if (Constants.isDevMode()) {
            List<String> strings = CharStreams.readLines(reader);
            fullJson = Joiner.on("\n").join(strings);
            reader = new StringReader(fullJson);
            Logger.i("Full http json: " + fullJson);
        }

        if (response.getStatusLine().getStatusCode() < 300) {
            result.setStatus(Status.SUCCESS);

            T output = gson.fromJson(reader, target);
            result.setContent(output);
        } else {
            result.setStatus(Status.FAILURE);

            Type type = new TypeToken<Map<String, String[]>>() {
            }.getType();
            Map<String, String[]> output = gson.fromJson(reader, type);
            result.setErrors(output);
        }
    } catch (Exception e) {
        Logger.e("Http request failed", e);
        result.setStatus(Status.ERROR);

        return result;
    } finally {
        closeQuietly(content);
        closeQuietly(reader);
        client.getConnectionManager().shutdown();
    }

    return result;
}

From source file:org.qi4j.library.shiro.web.WebRealmServiceTest.java

@Test
public void test() throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();

    // Our request method
    HttpGet get = new HttpGet("http://127.0.0.1:" + port + "/");

    HttpResponse response = client.execute(get);
    int status = response.getStatusLine().getStatusCode();

    assertThat(String.valueOf(status).substring(0, 1) + "xx", is("4xx"));

    EntityUtils.consume(response.getEntity());

    // Simple interceptor set as first interceptor in the protocol chain
    HttpRequestInterceptor preemptiveAuth = new BasicAuthRequestInterceptor();
    client.addRequestInterceptor(preemptiveAuth, 0);

    // Set credentials
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials("foo", "bar");
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

    response = client.execute(get);// w  w  w  .  j  a  v  a  2  s.  co  m
    status = response.getStatusLine().getStatusCode();

    assertThat(status, is(200));

    String result = new BasicResponseHandler().handleResponse(response).trim();
    assertThat(result, is("FOO"));
}

From source file:org.jfrog.build.client.PreemptiveHttpClient.java

private DefaultHttpClient createHttpClient(String userName, String password, int timeout) {
    BasicHttpParams params = new BasicHttpParams();
    int timeoutMilliSeconds = timeout * 1000;
    HttpConnectionParams.setConnectionTimeout(params, timeoutMilliSeconds);
    HttpConnectionParams.setSoTimeout(params, timeoutMilliSeconds);
    DefaultHttpClient client = new DefaultHttpClient(params);

    if (userName != null && !"".equals(userName)) {
        client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(userName, password));
        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);
    }//from   ww  w.j a  v  a  2  s  .  c  o  m
    boolean requestSentRetryEnabled = Boolean.parseBoolean(System.getProperty("requestSentRetryEnabled"));
    if (requestSentRetryEnabled) {
        client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, requestSentRetryEnabled));
    }
    // set the following user agent with each request
    String userAgent = "ArtifactoryBuildClient/" + CLIENT_VERSION;
    HttpProtocolParams.setUserAgent(client.getParams(), userAgent);
    return client;
}

From source file:com.controlj.experiment.bulktrend.trendclient.TrendClient.java

public void go() {
    DefaultHttpClient client = null;
    try {//w ww  . j a  va  2s. c om
        prepareForResponse();

        if (altInput == null) {
            client = new DefaultHttpClient();

            // Set up preemptive Basic Authentication
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);
            client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

            BasicHttpContext localcontext = new BasicHttpContext();
            BasicScheme basicAuth = new BasicScheme();
            localcontext.setAttribute("preemptive-auth", basicAuth);
            client.addRequestInterceptor(new PreemptiveAuthRequestInterceptor(), 0);

            if (zip) {
                client.addRequestInterceptor(new GZipRequestInterceptor());
                client.addResponseInterceptor(new GZipResponseInterceptor());
            }

            HttpPost post = new HttpPost(url);

            try {
                setPostData(post);
                HttpResponse response = client.execute(post, localcontext);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    System.err.println(
                            "Error: Web Service response code of: " + response.getStatusLine().getStatusCode());
                    return;
                }
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    parser.parseResponse(ids.size(), entity.getContent());
                }

            } catch (IOException e) {
                System.err.println("IO Error reading response");
                e.printStackTrace();
            }
        } else { // Alternate input (typically from a file) for testing
            try {
                parser.parseResponse(ids.size(), altInput);
            } catch (IOException e) {
                System.err.println("IO Error reading response");
                e.printStackTrace();
            }
        }
    } finally {
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
    }
    /*
    try {
    parser.parseResponse(ids.size(), new FileInputStream(new File("response.dump")));
    } catch (IOException e) {
    e.printStackTrace(); 
    }
    */

}

From source file:com.marvelution.hudson.plugins.apiv2.client.connectors.HttpClient4Connector.java

/**
 * Method to create the {@link HttpClient}
 * //ww  w.  ja  v  a2 s. c  om
 * @return the {@link DefaultHttpClient}
 */
private DefaultHttpClient createClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    if (server.isSecured()) {
        log.debug("The Server is secured, create the BasicHttpContext to handle preemptive authentication.");
        client.getCredentialsProvider().setCredentials(getAuthScope(),
                new UsernamePasswordCredentials(server.getUsername(), server.getPassword()));
        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 intercepter
        client.addRequestInterceptor(new PreemptiveAuth(), 0);
    }
    if (StringUtils.isNotBlank(System.getProperty("http.proxyHost"))
            || StringUtils.isNotBlank(System.getProperty("https.proxyHost"))) {
        log.debug("A System HTTP(S) proxy is set, set the ProxySelectorRoutePlanner for the client");
        System.setProperty("java.net.useSystemProxies", "true");
        // Set the ProxySelectorRoute Planner to automatically select the system proxy host if set.
        client.setRoutePlanner(new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(),
                ProxySelector.getDefault()));
    }
    return client;
}

From source file:com.mycompany.projecta.Test.java

public void Auth() throws Exception {

    // Credentials
    String username = "fernandoadp";
    String password = "ADP.2017";

    // Jenkins url
    String jenkinsUrl = "http://localhost:8080";

    // Build name
    String jobName = "ServiceA";

    // Build token
    String buildToken = "build";

    // Create your httpclient
    DefaultHttpClient client = new DefaultHttpClient();

    // Then provide the right credentials *******************
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new org.apache.http.auth.UsernamePasswordCredentials(username, password));
    //client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), (Credentials) new UsernamePasswordCredentials(username, password));

    // 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);

    // You get request that will start the build
    String getUrl = jenkinsUrl + "/job/" + jobName + "/build?token=" + buildToken;
    HttpGet get = new HttpGet(getUrl);

    try {/*from  ww w  . j  a  v a  2 s  .c  om*/
        // Execute your request with the given context
        HttpResponse response = client.execute(get, context);
        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.apache.manifoldcf.authorities.authorities.generic.GenericAuthority.java

protected DefaultHttpClient getClient() throws ManifoldCFException {
    synchronized (this) {
        if (client != null) {
            return client;
        }/*ww  w  .jav  a  2 s . c  o m*/
        DefaultHttpClient cl = new DefaultHttpClient();
        if (genericLogin != null && !genericLogin.isEmpty()) {
            try {
                URL url = new URL(genericEntryPoint);
                Credentials credentials = new UsernamePasswordCredentials(genericLogin, genericPassword);
                cl.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(),
                        url.getPort() > 0 ? url.getPort() : 80, AuthScope.ANY_REALM), credentials);
                cl.addRequestInterceptor(new PreemptiveAuth(credentials), 0);
            } catch (MalformedURLException ex) {
                client = null;
                sessionExpirationTime = -1L;
                throw new ManifoldCFException("getClient exception: " + ex.getMessage(), ex);
            }
        }
        HttpConnectionParams.setConnectionTimeout(cl.getParams(), connectionTimeoutMillis);
        HttpConnectionParams.setSoTimeout(cl.getParams(), socketTimeoutMillis);
        sessionExpirationTime = System.currentTimeMillis() + 300000L;
        client = cl;
        return cl;
    }
}