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() .
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 check out the related API usage on the sidebar.
Example 1
Source File: AsyncHttpClient.java From MiBandDecompiled with Apache License 2.0 | 6 votes |
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
Source File: HttpClientConfigurer.java From pushfish-android with BSD 2-Clause "Simplified" License | 5 votes |
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
Source File: HttpClientConfigurer.java From pushfish-android with BSD 2-Clause "Simplified" License | 5 votes |
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
Source File: HttpClientConfigurer.java From Pushjet-Android with BSD 2-Clause "Simplified" License | 5 votes |
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
Source File: HttpClientConfigurer.java From Pushjet-Android with BSD 2-Clause "Simplified" License | 5 votes |
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
Source File: WebRealmServiceTest.java From attic-polygene-java with Apache License 2.0 | 5 votes |
@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
Source File: CXFOAuth2HttpClientFactory.java From olingo-odata4 with Apache License 2.0 | 5 votes |
@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
Source File: AzureADOAuth2HttpClientFactory.java From olingo-odata4 with Apache License 2.0 | 5 votes |
@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
Source File: HttpClientFactory.java From cloudhopper-commons with Apache License 2.0 | 5 votes |
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
Source File: NetworkHelper.java From fanfouapp-opensource with Apache License 2.0 | 5 votes |
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 File: TestApp.java From gcpsamples with Apache License 2.0 | 4 votes |
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 File: TestApp.java From gcpsamples with Apache License 2.0 | 4 votes |
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
Source File: FusionKrb5HttpClientConfigurer.java From storm-solr with Apache License 2.0 | 4 votes |
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
Source File: SdcKrb5HttpClientConfigurer.java From datacollector with Apache License 2.0 | 4 votes |
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 File: HttpRequestHelper.java From YiBo with Apache License 2.0 | 4 votes |
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; }