List of usage examples for org.apache.http.impl.client DefaultHttpClient addRequestInterceptor
public synchronized void addRequestInterceptor(final HttpRequestInterceptor itcp, final int index)
From source file:httpclient.client.ClientPreemptiveBasicAuthentication.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials(new AuthScope("localhost", 80), 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 httpclient.addRequestInterceptor(new PreemptiveAuth(), 0); HttpHost targetHost = new HttpHost("localhost", 80, "http"); HttpGet httpget = new HttpGet("/"); System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("to target: " + targetHost); for (int i = 0; i < 3; i++) { HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); entity.consumeContent();//from w w w . j av a 2s .c om } } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); }
From source file:httpclient.client.ClientPreemptiveDigestAuthentication.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials(new AuthScope("localhost", 80), new UsernamePasswordCredentials("username", "password")); BasicHttpContext localcontext = new BasicHttpContext(); // Generate DIGEST scheme object, initialize it and stick it to // the local execution context DigestScheme digestAuth = new DigestScheme(); // Suppose we already know the realm name digestAuth.overrideParamter("realm", "some realm"); // Suppose we already know the expected nonce value digestAuth.overrideParamter("nonce", "whatever"); localcontext.setAttribute("preemptive-auth", digestAuth); // Add as the first request interceptor httpclient.addRequestInterceptor(new PreemptiveAuth(), 0); // Add as the last response interceptor httpclient.addResponseInterceptor(new PersistentDigest()); HttpHost targetHost = new HttpHost("localhost", 80, "http"); HttpGet httpget = new HttpGet("/"); System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("to target: " + targetHost); for (int i = 0; i < 3; i++) { HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); entity.consumeContent();/*from w w w . ja va 2 s. c o m*/ } } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); }
From source file:com.cloudhopper.httpclient.util.HttpPostMain.java
static public void main(String[] args) throws Exception { ///* ww w.ja v a2 s. c o m*/ // target urls // String strURL = "http://209.226.31.233:9009/SendSmsService/b98183b99a1f473839ce569c78b84dbd"; // Username: Twitter // Password: Twitter123 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); // for (int i = 0; i < 1; i++) { // // create a new ticket id // //String ticketId = TicketUtil.generate(1, System.currentTimeMillis()); /** StringBuilder string0 = new StringBuilder(200) .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n") .append(" <S:Header>\n") .append(" <ns3:TransactionID xmlns:ns4=\"http://vmp.vzw.com/schema\"\n") .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\">" + ticketId + "</ns3:TransactionID>\n") .append(" </S:Header>\n") .append(" <S:Body>\n") .append(" <ns2:OptinReq xmlns:ns4=\"http://schemas.xmlsoap.org/soap/envelope/\"\n") .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\"\n") .append("xmlns:ns2=\"http://vmp.vzw.com/schema\">\n") .append(" <ns2:VASPID>twitter</ns2:VASPID>\n") .append(" <ns2:VASID>tm33t!</ns2:VASID>\n") .append(" <ns2:ShortCode>800080008001</ns2:ShortCode>\n") .append(" <ns2:Number>9257089093</ns2:Number>\n") .append(" <ns2:Source>provider</ns2:Source>\n") .append(" <ns2:Message/>\n") .append(" </ns2:OptinReq>\n") .append(" </S:Body>\n") .append("</S:Envelope>"); */ // simple send sms StringBuilder string1 = new StringBuilder(200).append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:loc=\"http://www.csapi.org/schema/parlayx/sms/send/v2_3/local\">\n") .append(" <soapenv:Header/>\n").append(" <soapenv:Body>\n").append(" <loc:sendSms>\n") .append(" <loc:addresses>tel:+16472260233</loc:addresses>\n") .append(" <loc:senderName>6388</loc:senderName>\n") .append(" <loc:message>Test Message &</loc:message>\n").append(" </loc:sendSms>\n") .append(" </soapenv:Body>\n").append("</soapenv:Envelope>\n"); // startSmsNotification - place to deliver SMS to String req = string1.toString(); logger.debug("Request XML -> \n" + req); HttpPost post = new HttpPost(strURL); StringEntity postEntity = new StringEntity(req, "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("209.226.31.233", AuthScope.ANY_PORT), new UsernamePasswordCredentials("Twitter", "Twitter123")); 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(); // // was the request OK? // if (httpResponse.getStatusLine().getStatusCode() != 200) { logger.error("Request failed with StatusCode=" + httpResponse.getStatusLine().getStatusCode()); } // get an input stream String responseBody = EntityUtils.toString(responseEntity); long stop = System.currentTimeMillis(); logger.debug("----------------------------------------"); logger.debug("Response took " + (stop - start) + " ms"); logger.debug(responseBody); logger.debug("----------------------------------------"); // } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources client.getConnectionManager().shutdown(); }
From source file:org.nuxeo.scim.server.tests.ScimServerTest.java
protected static ClientConfig createHttpBasicClientConfig(final String userName, final String password) { final HttpParams params = new BasicHttpParams(); DefaultHttpClient.setDefaultHttpParams(params); params.setBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, true); params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true); final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); final PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(schemeRegistry); mgr.setMaxTotal(200);// w w w . ja va2 s . com mgr.setDefaultMaxPerRoute(20); final DefaultHttpClient httpClient = new DefaultHttpClient(mgr, params); final Credentials credentials = new UsernamePasswordCredentials(userName, password); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0); ClientConfig clientConfig = new ApacheHttpClientConfig(httpClient); clientConfig.setBypassHostnameVerification(true); return clientConfig; }
From source file:com.unboundid.scim.sdk.examples.ClientExample.java
/** * Create an SSL-enabled Wink client config from the provided information. * The returned client config may be used to create a SCIM service object. * IMPORTANT: This should not be used in production because no validation * is performed on the server certificate returned by the SCIM service. * * @param userName The HTTP Basic Auth user name. * @param password The HTTP Basic Auth password. * * @return An Apache Wink client config. *///from www . j av a2 s . c o m public static ClientConfig createHttpBasicClientConfig(final String userName, final String password) { SSLSocketFactory sslSocketFactory; try { final SSLContext sslContext = SSLContext.getInstance("TLS"); // Do not use these settings in production. sslContext.init(null, new TrustManager[] { new BlindTrustManager() }, new SecureRandom()); sslSocketFactory = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (KeyManagementException e) { throw new RuntimeException(e.getLocalizedMessage()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getLocalizedMessage()); } final HttpParams params = new BasicHttpParams(); DefaultHttpClient.setDefaultHttpParams(params); params.setBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, true); params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true); final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, sslSocketFactory)); final PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(schemeRegistry); mgr.setMaxTotal(200); mgr.setDefaultMaxPerRoute(20); final DefaultHttpClient httpClient = new DefaultHttpClient(mgr, params); final Credentials credentials = new UsernamePasswordCredentials(userName, password); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0); ClientConfig clientConfig = new ApacheHttpClientConfig(httpClient); clientConfig.setBypassHostnameVerification(true); return clientConfig; }
From source file:com.cloudhopper.httpclient.util.HttpClientFactory.java
static public void configureWithPreemptiveBasicAuth(DefaultHttpClient client, String username, String passsword) {/*from ww w.j a v a 2s . co m*/ // // 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); }
From source file:com.daskiworks.ghwatch.backend.RemoteSystemClient.java
protected static DefaultHttpClient prepareHttpClient(URI uri, GHCredentials apiCredentials) { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, 30000); HttpConnectionParams.setSoTimeout(params, 30000); httpClient.addRequestInterceptor(preemptiveAuth, 0); if (apiCredentials != null) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_SCHEME), new UsernamePasswordCredentials(apiCredentials.getUsername(), apiCredentials.getPassword())); }/*from www. ja v a 2s . c o m*/ return httpClient; }
From source file:net.homelinux.penecoptero.android.citybikes.app.RESTHelper.java
private static DefaultHttpClient setCredentials(DefaultHttpClient httpclient, String url, String username, String password) throws HttpException, IOException { HttpHost targetHost = new HttpHost(url); final UsernamePasswordCredentials access = new UsernamePasswordCredentials(username, password); httpclient.getCredentialsProvider()/*from w ww .j ava 2s . com*/ .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:se.vgregion.util.HTTPUtils.java
public static HttpResponse basicAuthRequest(String url, String username, String password, DefaultHttpClient client) throws HttpUtilsException { HttpGet get = new HttpGet(url); client.getCredentialsProvider().setCredentials(new AuthScope(null, 443), 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 response;/*from www.j ava 2 s. co m*/ try { response = client.execute(get, localcontext); } catch (ClientProtocolException e) { throw new HttpUtilsException("Invalid http protocol", e); } catch (IOException e) { throw new HttpUtilsException(e.getMessage(), e); } return response; }
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 a v a 2 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; }