List of usage examples for org.apache.http.impl.client HttpClientBuilder build
public CloseableHttpClient build()
From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java
public static HttpClient getDefaultHttpsClient() { try {/*from www . j av a 2 s. c om*/ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new DefaultSecureSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpConnectionParams.setConnectionTimeout(params, 300000); HttpConnectionParams.setSocketBufferSize(params, 10485760); HttpConnectionParams.setSoTimeout(params, 300000); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params); HttpClientBuilder b = HttpClientBuilder.create(); return b.build(); //return httpClient; } catch (Exception e) { e.printStackTrace(); return new DefaultHttpClient(); } }
From source file:io.fabric8.maven.support.Apps.java
/** * Posts a file to the git repository/*from ww w. ja va2s .co m*/ */ public static HttpResponse postFileToGit(File file, String user, String password, String consoleUrl, String branch, String path, Logger logger) throws URISyntaxException, IOException { HttpClientBuilder builder = HttpClients.custom(); if (Strings.isNotBlank(user) && Strings.isNotBlank(password)) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", 443), new UsernamePasswordCredentials(user, password)); builder = builder.setDefaultCredentialsProvider(credsProvider); } CloseableHttpClient client = builder.build(); try { String url = consoleUrl; if (!url.endsWith("/")) { url += "/"; } url += "git/"; url += branch; if (!path.startsWith("/")) { url += "/"; } url += path; logger.info("Posting App Zip " + file.getName() + " to " + url); URI buildUrl = new URI(url); HttpPost post = new HttpPost(buildUrl); // use multi part entity format FileBody zip = new FileBody(file); HttpEntity entity = MultipartEntityBuilder.create().addPart(file.getName(), zip).build(); post.setEntity(entity); // post.setEntity(new FileEntity(file)); HttpResponse response = client.execute(URIUtils.extractHost(buildUrl), post); logger.info("Response: " + response); if (response != null) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < 200 || statusCode >= 300) { throw new IllegalStateException("Failed to post App Zip to: " + url + " " + response); } } return response; } finally { Closeables.closeQuietly(client); } }
From source file:com.github.pascalgn.jiracli.web.HttpClient.java
private static CloseableHttpClient createHttpClient() { HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setSSLSocketFactory(SSL_SOCKET_FACTORY); return httpClientBuilder.build(); }
From source file:com.granita.icloudcalsync.webdav.DavHttpClient.java
@SuppressLint("LogTagMismatch") public static CloseableHttpClient create() { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry);/*from w w w .ja v a 2 s . c o m*/ // limits per DavHttpClient (= per DavSyncAdapter extends AbstractThreadedSyncAdapter) connectionManager.setMaxTotal(3); // max. 3 connections in total connectionManager.setDefaultMaxPerRoute(2); // max. 2 connections per host HttpClientBuilder builder = HttpClients.custom().useSystemProperties() .setConnectionManager(connectionManager).setDefaultRequestConfig(defaultRqConfig) .setRetryHandler(DavHttpRequestRetryHandler.INSTANCE) .setRedirectStrategy(DavRedirectStrategy.INSTANCE) .setUserAgent("DAVdroid/" + Constants.APP_VERSION); if (Log.isLoggable("Wire", Log.DEBUG)) { Log.i(TAG, "Wire logging active, disabling HTTP compression"); builder = builder.disableContentCompression(); } return builder.build(); }
From source file:groovesquid.Grooveshark.java
public static String sendRequest(String method, HashMap<String, Object> parameters) { if (tokenExpires <= new Date().getTime() && tokenExpires != 0 && !"initiateSession".equals(method) && !"getCommunicationToken".equals(method) && !"getCountry".equals(method)) { try {/* w ww . j a v a 2 s . c om*/ InitThread initThread = new InitThread(); initThread.start(); initThread.getLatch().await(); } catch (InterruptedException ex) { log.log(Level.SEVERE, null, ex); } } String responseContent = null; HttpEntity httpEntity = null; try { Client client = clients.getHtmlshark(); String protocol = "http://"; if (method.equals("getCommunicationToken")) { protocol = "https://"; } String url = protocol + "grooveshark.com/more.php?" + method; for (String jsqueueMethod : jsqueueMethods) { if (jsqueueMethod.equals(method)) { client = clients.getJsqueue(); break; } } header.put("client", client.getName()); header.put("clientRevision", client.getRevision()); header.put("privacy", "0"); header.put("uuid", uuid); header.put("country", country); if (!method.equals("initiateSession")) { header.put("session", session); header.put("token", generateToken(method, client.getSecret())); } Gson gson = new Gson(); String jsonString = gson.toJson(new JsonRequest(header, parameters, method)); log.info(">>> " + jsonString); HttpPost httpPost = new HttpPost(url); httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json"); httpPost.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); httpPost.setHeader(HTTP.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31"); httpPost.setHeader("Referer", "http://grooveshark.com/JSQueue.swf?" + client.getRevision()); httpPost.setHeader("Content-Language", "en-US"); httpPost.setHeader("Cache-Control", "max-age=0"); httpPost.setHeader("Accept", "*/*"); httpPost.setHeader("Accept-Charset", "utf-8,ISO-8859-1;q=0.7,*;q=0.3"); httpPost.setHeader("Accept-Language", "de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4"); httpPost.setHeader("Accept-Encoding", "gzip,deflate,sdch"); httpPost.setHeader("Origin", "http://grooveshark.com"); if (!method.equals("initiateSession")) { httpPost.setHeader("Cookie", "PHPSESSID=" + session); } httpPost.setEntity(new StringEntity(jsonString, "UTF-8")); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); if (Main.getConfig().getProxyHost() != null && Main.getConfig().getProxyPort() != null) { httpClientBuilder .setProxy(new HttpHost(Main.getConfig().getProxyHost(), Main.getConfig().getProxyPort())); } HttpClient httpClient = httpClientBuilder.build(); HttpResponse httpResponse = httpClient.execute(httpPost); ByteArrayOutputStream baos = new ByteArrayOutputStream(); httpEntity = httpResponse.getEntity(); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == HttpStatus.SC_OK) { httpEntity.writeTo(baos); } else { throw new RuntimeException("method " + method + ": " + statusLine); } responseContent = baos.toString("UTF-8"); } catch (Exception ex) { Logger.getLogger(Grooveshark.class.getName()).log(Level.SEVERE, null, ex); } finally { try { EntityUtils.consume(httpEntity); } catch (IOException ex) { Logger.getLogger(Grooveshark.class.getName()).log(Level.SEVERE, null, ex); } } log.info("<<< " + responseContent); return responseContent; }
From source file:com.ibm.watson.developer_cloud.professor_languo.ingestion.RankerCreationUtil.java
/** * /*from ww w.j ava 2s.c o m*/ * @param uri * @param username * @param password * @return */ public static HttpClient createHttpClient(String uri, String username, String password) { final URI scopeUri = URI.create(uri); final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()), new UsernamePasswordCredentials(username, password)); final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32) .setDefaultRequestConfig( RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build()); builder.setDefaultCredentialsProvider(credentialsProvider); return builder.build(); }
From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java
public static String sendHttpGetForSAMLSSO(String url, String user, String password, int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception { CloseableHttpClient httpClient = null; try {/*from www. j a va 2 s. c om*/ CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", idpPort), new UsernamePasswordCredentials(user, password)); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks")); try { trustStore.load(instream, "clientpass".toCharArray()); } finally { try { instream.close(); } catch (Exception ex) { ex.printStackTrace(); } } SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray()); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); httpClient = httpClientBuilder.build(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode()); return EntityUtils.toString(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources if (httpClient != null) { httpClient.close(); } } }
From source file:org.apache.cxf.fediz.integrationtests.KerberosTest.java
public static String sendHttpGet(String url, String ticket, int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception { CloseableHttpClient httpClient = null; try {/* ww w . ja v a2s. co m*/ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks")); try { trustStore.load(instream, "clientpass".toCharArray()); } finally { try { instream.close(); } catch (Exception ex) { ex.printStackTrace(); } } SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray()); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); httpClient = httpClientBuilder.build(); HttpGet httpget = new HttpGet(url); httpget.addHeader("Authorization", "Negotiate " + ticket); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != 200) { return null; } // Redirect to a POST is not supported without user interaction // http://www.ietf.org/rfc/rfc2616.txt // If the 301 status code is received in response to a request other // than GET or HEAD, the user agent MUST NOT automatically redirect the // request unless it can be confirmed by the user, since this might // change the conditions under which the request was issued. Source source = new Source(EntityUtils.toString(entity)); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); FormFields formFields = source.getFormFields(); List<Element> forms = source.getAllElements(HTMLElementName.FORM); Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size()); String postUrl = forms.get(0).getAttributeValue("action"); Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa")); Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult")); for (FormField formField : formFields) { if (formField.getUserValueCount() != 0) { nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0))); } } HttpPost httppost = new HttpPost(postUrl); httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); response = httpClient.execute(httppost); entity = response.getEntity(); System.out.println(response.getStatusLine()); Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } return EntityUtils.toString(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources if (httpClient != null) { httpClient.close(); } } }
From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java
/** * Same as sendHttpGet above, except that we return the HttpClient so that it can * subsequently be re-used (for e.g. logout) *///from www. j av a 2 s. c o m public static CloseableHttpClient sendHttpGetForSignIn(String url, String user, String password, int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception { CloseableHttpClient httpClient = null; CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", idpPort), new UsernamePasswordCredentials(user, password)); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks")); try { trustStore.load(instream, "clientpass".toCharArray()); } finally { try { instream.close(); } catch (Exception ex) { ex.printStackTrace(); } } SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray()); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); httpClient = httpClientBuilder.build(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != 200) { return null; } // Redirect to a POST is not supported without user interaction // http://www.ietf.org/rfc/rfc2616.txt // If the 301 status code is received in response to a request other // than GET or HEAD, the user agent MUST NOT automatically redirect the // request unless it can be confirmed by the user, since this might // change the conditions under which the request was issued. Source source = new Source(EntityUtils.toString(entity)); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); FormFields formFields = source.getFormFields(); List<Element> forms = source.getAllElements(HTMLElementName.FORM); Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size()); String postUrl = forms.get(0).getAttributeValue("action"); Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa")); Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult")); for (FormField formField : formFields) { if (formField.getUserValueCount() != 0) { nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0))); } } HttpPost httppost = new HttpPost(postUrl); httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); response = httpClient.execute(httppost); entity = response.getEntity(); Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode()); String responseStr = EntityUtils.toString(entity); Assert.assertTrue("Principal not " + user, responseStr.indexOf("userPrincipal=" + user) > 0); return httpClient; }
From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java
public static String sendHttpGet(String url, String user, String password, int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception { CloseableHttpClient httpClient = null; try {/*from w w w .j av a 2 s. c o m*/ CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", idpPort), new UsernamePasswordCredentials(user, password)); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks")); try { trustStore.load(instream, "clientpass".toCharArray()); } finally { try { instream.close(); } catch (Exception ex) { ex.printStackTrace(); } } SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray()); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); httpClient = httpClientBuilder.build(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != 200) { return null; } // Redirect to a POST is not supported without user interaction // http://www.ietf.org/rfc/rfc2616.txt // If the 301 status code is received in response to a request other // than GET or HEAD, the user agent MUST NOT automatically redirect the // request unless it can be confirmed by the user, since this might // change the conditions under which the request was issued. Source source = new Source(EntityUtils.toString(entity)); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); FormFields formFields = source.getFormFields(); List<Element> forms = source.getAllElements(HTMLElementName.FORM); Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size()); String postUrl = forms.get(0).getAttributeValue("action"); Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa")); Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult")); for (FormField formField : formFields) { if (formField.getUserValueCount() != 0) { nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0))); } } HttpPost httppost = new HttpPost(postUrl); httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); response = httpClient.execute(httppost); entity = response.getEntity(); System.out.println(response.getStatusLine()); Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } return EntityUtils.toString(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources if (httpClient != null) { httpClient.close(); } } }