Java Code Examples for org.apache.http.impl.client.DefaultHttpClient#addRequestInterceptor()

The following examples show how to use org.apache.http.impl.client.DefaultHttpClient#addRequestInterceptor() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
public AsyncHttpClient(SchemeRegistry schemeregistry)
{
    a = 10;
    b = 10000;
    h = true;
    BasicHttpParams basichttpparams = new BasicHttpParams();
    ConnManagerParams.setTimeout(basichttpparams, b);
    ConnManagerParams.setMaxConnectionsPerRoute(basichttpparams, new ConnPerRouteBean(a));
    ConnManagerParams.setMaxTotalConnections(basichttpparams, 10);
    HttpConnectionParams.setSoTimeout(basichttpparams, b);
    HttpConnectionParams.setConnectionTimeout(basichttpparams, b);
    HttpConnectionParams.setTcpNoDelay(basichttpparams, true);
    HttpConnectionParams.setSocketBufferSize(basichttpparams, 8192);
    HttpProtocolParams.setVersion(basichttpparams, HttpVersion.HTTP_1_1);
    ThreadSafeClientConnManager threadsafeclientconnmanager = new ThreadSafeClientConnManager(basichttpparams, schemeregistry);
    e = getDefaultThreadPool();
    f = new WeakHashMap();
    g = new HashMap();
    d = new SyncBasicHttpContext(new BasicHttpContext());
    c = new DefaultHttpClient(threadsafeclientconnmanager, basichttpparams);
    c.addRequestInterceptor(new a(this));
    c.addResponseInterceptor(new b(this));
    c.addRequestInterceptor(new c(this), 0);
    c.setHttpRequestRetryHandler(new z(5, 1500));
}
 
Example 2
private void configureCredentials(DefaultHttpClient httpClient, PasswordCredentials credentials) {
    String username = credentials.getUsername();
    if (username != null && username.length() > 0) {
        useCredentials(httpClient, credentials, AuthScope.ANY_HOST, AuthScope.ANY_PORT);

        // Use preemptive authorisation if no other authorisation has been established
        httpClient.addRequestInterceptor(new PreemptiveAuth(new BasicScheme()), 0);
    }
}
 
Example 3
private void configureCredentials(DefaultHttpClient httpClient, PasswordCredentials credentials) {
    if (GUtil.isTrue(credentials.getUsername())) {
        useCredentials(httpClient, credentials, AuthScope.ANY_HOST, AuthScope.ANY_PORT);

        // Use preemptive authorisation if no other authorisation has been established
        httpClient.addRequestInterceptor(new PreemptiveAuth(new BasicScheme()), 0);
    }
}
 
Example 4
private void configureCredentials(DefaultHttpClient httpClient, PasswordCredentials credentials) {
    String username = credentials.getUsername();
    if (username != null && username.length() > 0) {
        useCredentials(httpClient, credentials, AuthScope.ANY_HOST, AuthScope.ANY_PORT);

        // Use preemptive authorisation if no other authorisation has been established
        httpClient.addRequestInterceptor(new PreemptiveAuth(new BasicScheme()), 0);
    }
}
 
Example 5
private void configureCredentials(DefaultHttpClient httpClient, PasswordCredentials credentials) {
    if (GUtil.isTrue(credentials.getUsername())) {
        useCredentials(httpClient, credentials, AuthScope.ANY_HOST, AuthScope.ANY_PORT);

        // Use preemptive authorisation if no other authorisation has been established
        httpClient.addRequestInterceptor(new PreemptiveAuth(new BasicScheme()), 0);
    }
}
 
Example 6
@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 );
    status = response.getStatusLine().getStatusCode();

    assertThat( status, is( 200 ) );

    String result = new BasicResponseHandler().handleResponse( response ).trim();
    assertThat( result, is( "FOO" ) );
}
 
Example 7
@Override
protected void accessToken(final DefaultHttpClient client) throws OAuth2Exception {
  client.addRequestInterceptor(new HttpRequestInterceptor() {

    @Override
    public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
      request.removeHeaders(HttpHeaders.AUTHORIZATION);
      request.addHeader(HttpHeaders.AUTHORIZATION, OAuthClientUtils.createAuthorizationHeader(accessToken));
    }
  });
}
 
Example 8
@Override
protected void accessToken(final DefaultHttpClient client) throws OAuth2Exception {
  client.addRequestInterceptor(new HttpRequestInterceptor() {

    @Override
    public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
      request.removeHeaders(HttpHeaders.AUTHORIZATION);
      request.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token.get("access_token").asText());
    }
  });
}
 
Example 9
static public void configureWithPreemptiveBasicAuth(DefaultHttpClient client, String username, String passsword) {
    //
    // create a new request interceptor that includes adding basic auth
    //
    PreemptiveBasicAuthHttpRequestInterceptor interceptor = new PreemptiveBasicAuthHttpRequestInterceptor();

    // set credentials
    interceptor.setCredentials(username, passsword);

    // add as the first request interceptor
    client.addRequestInterceptor(interceptor, 0);
}
 
Example 10
public final static DefaultHttpClient createHttpClient(final Context context) {
    final HttpParams params = NetworkHelper.createHttpParams();
    final DefaultHttpClient client = new DefaultHttpClient(params);
    client.addRequestInterceptor(new GzipRequestInterceptor());
    client.addResponseInterceptor(new GzipResponseInterceptor());
    client.setHttpRequestRetryHandler(new RequestRetryHandler(
            NetworkHelper.MAX_RETRY_TIMES));
    NetworkHelper.checkAndSetProxy(context, params);
    return client;
}
 
Example 11
Source Project: gcpsamples   File: TestApp.java    License: Apache License 2.0 4 votes vote down vote up
public TestApp()  {

    String projectId = ServiceOptions.getDefaultProjectId();
	try {

		//export GRPC_PROXY_EXP=localhost:3128
		HttpHost proxy = new HttpHost("127.0.0.1",3128);
		DefaultHttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
					
		httpClient.addRequestInterceptor(new HttpRequestInterceptor(){            
			@Override
			public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException {
					//if (request.getRequestLine().getMethod().equals("CONNECT"))                 
					//   request.addHeader(new BasicHeader("Proxy-Authorization","Basic dXNlcjE6dXNlcjE="));
				}
			});
		
		mHttpTransport =  new ApacheHttpTransport(httpClient);		

		HttpTransportFactory hf = new HttpTransportFactory(){
			@Override
			public HttpTransport create() {
				return mHttpTransport;
			}
		};            
		
		credential = GoogleCredentials.getApplicationDefault(hf);

		CredentialsProvider credentialsProvider =  new GoogleCredentialsProvider(){
			public List<String> getScopesToApply(){
				return Arrays.asList("https://www.googleapis.com/auth/pubsub");
			   }

			public Credentials getCredentials()  {
				return credential;
			}
		};

		TopicAdminSettings topicAdminSettings =
		     TopicAdminSettings.newBuilder().setCredentialsProvider(credentialsProvider)
				 .build();
				 
		 TopicAdminClient topicAdminClient =
		     TopicAdminClient.create(topicAdminSettings);
		
		//TopicAdminClient topicAdminClient = TopicAdminClient.create();
		ProjectName project = ProjectName.create(projectId);
		for (Topic element : topicAdminClient.listTopics(project).iterateAll()) 
	  		System.out.println(element.getName());
	
	} catch (Exception ex) 
	{
		System.out.println("ERROR " + ex);
	}
  }
 
Example 12
Source Project: gcpsamples   File: TestApp.java    License: Apache License 2.0 4 votes vote down vote up
public TestApp() {
        try
        {
            
            /*
          JacksonFactory jsonFactory = new JacksonFactory(); 
              
            Authenticator.setDefault(
                new Authenticator() {
                   @Override
                   public PasswordAuthentication getPasswordAuthentication() {
                      return new PasswordAuthentication(
                            "user1", "user1".toCharArray());
                   }
                }
             );                          
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 3128));
            NetHttpTransport mHttpTransport = new NetHttpTransport.Builder().setProxy(proxy).build();
            */
           

            HttpHost proxy = new HttpHost("127.0.0.1",3128);
            DefaultHttpClient httpClient = new DefaultHttpClient();
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            
            httpClient.addRequestInterceptor(new HttpRequestInterceptor(){            
                @Override
                public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException {
                    //if (request.getRequestLine().getMethod().equals("CONNECT"))                 
                    //  request.addHeader(new BasicHeader("Proxy-Authorization","Basic dXNlcjE6dXNlcjE="));
                }
            });

           mHttpTransport =  new ApacheHttpTransport(httpClient);



/*
            com.google.api.client.googleapis.auth.oauth2.GoogleCredential credential = com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(mHttpTransport,jsonFactory);
            if (credential.createScopedRequired())
                credential = credential.createScoped(Arrays.asList(StorageScopes.DEVSTORAGE_READ_ONLY));

            com.google.api.services.storage.Storage service = new com.google.api.services.storage.Storage.Builder(mHttpTransport, jsonFactory, credential)
                .setApplicationName("oauth client")   
                .build(); 
                
            com.google.api.services.storage.model.Buckets dl = service.buckets().list("mineral-minutia-820").execute();
            for (com.google.api.services.storage.model.Bucket bucket: dl.getItems()) 
                System.out.println(bucket.getName());
*/

            
           // System.setProperty("https.proxyHost", "localhost");
           // System.setProperty("https.proxyPort", "3128");
/*
            Authenticator.setDefault(
                new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(
                            "user1", "user1".toCharArray());
                }
                }
            );
*/


            HttpTransportFactory hf = new HttpTransportFactory(){
                @Override
                public HttpTransport create() {
                    return mHttpTransport;
                }
            };            

            com.google.auth.oauth2.GoogleCredentials credential = com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(hf);
            if (credential.createScopedRequired())
                credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/devstorage.read_write"));

            TransportOptions options = HttpTransportOptions.newBuilder().setHttpTransportFactory(hf).build();            
            com.google.cloud.storage.Storage storage = com.google.cloud.storage.StorageOptions.newBuilder()
                .setCredentials(credential)
                .setProjectId("mineral-minutia-820")
                .setTransportOptions(options)
                .build().getService();
            
            System.out.println("My buckets:");        
            for (com.google.cloud.storage.Bucket bucket : storage.list().iterateAll()) 
              System.out.println(bucket);              
          
        } 
        catch (Exception ex) {
            System.out.println("Error:  " + ex);
        }
    
    }
 
Example 13
public void configure(DefaultHttpClient httpClient, SolrParams config) {
  super.configure(httpClient, config);
  if (System.getProperty(LOGIN_CONFIG_PROP) != null) {
    String configValue = System.getProperty(LOGIN_CONFIG_PROP);
    if (configValue != null) {
      logger.debug("Setting up kerberos auth with config: " + configValue);
      System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

      if (fusionPrincipal != null) {
        Subject subject = new Subject(false, Sets.newHashSet(new KerberosPrincipal(fusionPrincipal)),
            Collections.emptySet(), Collections.emptySet());
        LoginContext loginContext;
        try {
          loginContext = new LoginContext("", subject, null, jaasConfig);
          loginContext.login();
          logger.debug("Successful Fusion Login with principal: " + fusionPrincipal);
        } catch (LoginException e) {
          String errorMessage = "Unsuccessful Fusion Login with principal: " + fusionPrincipal;
          logger.error(errorMessage, e);
          throw new RuntimeException(errorMessage, e);
        }
      }

      Configuration.setConfiguration(jaasConfig);
      httpClient.getAuthSchemes().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, false));
      Credentials useJaasCreds = new Credentials() {
        public String getPassword() {
          return null;
        }

        public Principal getUserPrincipal() {
          return null;
        }
      };
      httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, useJaasCreds);
      httpClient.addRequestInterceptor(this.bufferedEntityInterceptor);
    } else {
      httpClient.getCredentialsProvider().clear();
    }
  }
}
 
Example 14
public void configure(DefaultHttpClient httpClient, SolrParams config) {
  super.configure(httpClient, config);

  // Begin change for SDC-2962
  // Instead of checking existence of JAAS file, do the following if solr kerberos is enabled
  //if (System.getProperty(LOGIN_CONFIG_PROP) != null) {
    //String configValue = System.getProperty(LOGIN_CONFIG_PROP);

    //if (configValue != null) {
     // logger.info("Setting up SPNego auth with config: " + configValue);
      final String useSubjectCredsProp = "javax.security.auth.useSubjectCredsOnly";
      String useSubjectCredsVal = System.getProperty(useSubjectCredsProp);

      // "javax.security.auth.useSubjectCredsOnly" should be false so that the underlying
      // authentication mechanism can load the credentials from the JAAS configuration.
      if (useSubjectCredsVal == null) {
        System.setProperty(useSubjectCredsProp, "false");
      }
      else if (!useSubjectCredsVal.toLowerCase(Locale.ROOT).equals("false")) {
        // Don't overwrite the prop value if it's already been written to something else,
        // but log because it is likely the Credentials won't be loaded correctly.
        logger.warn("System Property: " + useSubjectCredsProp + " set to: " + useSubjectCredsVal
            + " not false.  SPNego authentication may not be successful.");
      }

      // Change for SDC-2962
      //javax.security.auth.login.Configuration.setConfiguration(jaasConfig);
      //Enable only SPNEGO authentication scheme.
      AuthSchemeRegistry registry = new AuthSchemeRegistry();
      registry.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, false));
      httpClient.setAuthSchemes(registry);
      // Get the credentials from the JAAS configuration rather than here
      Credentials useJaasCreds = new Credentials() {
        public String getPassword() {
          return null;
        }
        public Principal getUserPrincipal() {
          return null;
        }
      };

      SolrPortAwareCookieSpecFactory cookieFactory = new SolrPortAwareCookieSpecFactory();
      httpClient.getCookieSpecs().register(cookieFactory.POLICY_NAME, cookieFactory);
      httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, cookieFactory.POLICY_NAME);

      httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, useJaasCreds);

      httpClient.addRequestInterceptor(bufferedEntityInterceptor);
    //} else {
      //httpClient.getCredentialsProvider().clear();
    //}
 // }
}
 
Example 15
Source Project: YiBo   File: HttpRequestHelper.java    License: Apache License 2.0 4 votes vote down vote up
private static synchronized HttpClient createHttpClient(HttpConfig config) {
	if (config == null) {
		return null;
	}

	if (connectionManager == null) {
		connectionManager = createConnectionManager();
	}

	HttpParams httpParams = new BasicHttpParams();

	if (config.getHttpConnectionTimeout() > 0) {
		httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
			config.getHttpConnectionTimeout());
	}
	if (config.getHttpReadTimeout() > 0) {
		httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getHttpReadTimeout());
	}
	// 设置cookie策略
    httpParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
			
	// 设置http.protocol.expect-continue参数为false,即不使用Expect:100-Continue握手,
	// 因为如果服务器不支持HTTP 1.1,则会导致HTTP 417错误。
	HttpProtocolParams.setUseExpectContinue(httpParams, false);
	// 设置User-Agent
	HttpProtocolParams.setUserAgent(httpParams, config.getUserAgent());
	// 设置HTTP版本为 HTTP 1.1
	HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

	DefaultHttpClient httpClient = new LibHttpClient(connectionManager, httpParams);

	updateProxySetting(config, httpClient);

	if (config.isUseGzip()) {
		httpClient.addRequestInterceptor(new GzipRequestInterceptor());
		httpClient.addResponseInterceptor(new GzipResponseInterceptor());
	}
	if (config.getHttpRetryCount() > 0) {
		HttpRequestRetryHandler retryHandler =
			new DefaultHttpRequestRetryHandler(config.getHttpRetryCount(), true);
		httpClient.setHttpRequestRetryHandler(retryHandler);
	}

	return httpClient;
}