List of usage examples for org.apache.http.client HttpClient getParams
@Deprecated HttpParams getParams();
From source file:org.bigmouth.nvwa.network.http.HttpClientHelper.java
public static HttpClient http(int timeout) { HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreConnectionPNames.SO_KEEPALIVE, true); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); return httpClient; }
From source file:org.egov.android.view.activity.RegisterActivity.java
/** * Get cities list json from app config url *///from www . jav a 2s.com public String getJSON(String address) { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(address); try { HttpParams params = client.getParams(); HttpConnectionParams.setConnectionTimeout(params, (60 * 1000)); HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(RegisterActivity.class.toString(), "Failedet JSON object"); } } catch (ClientProtocolException e) { e.printStackTrace(); return "ERROR"; } catch (IOException e) { e.printStackTrace(); return "ERROR"; } return builder.toString(); }
From source file:org.jboss.as.test.integration.management.api.web.ConnectorTestCase.java
public static HttpClient wrapClient(HttpClient base) { try {/*from www . ja v a 2 s . c o m*/ SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); return new DefaultHttpClient(ccm, base.getParams()); } catch (Exception ex) { ex.printStackTrace(); return null; } }
From source file:org.jenkinsci.plugins.skytap.SkytapUtils.java
/** * Utility method to execute any type of http request (except delete), to * catch any exceptions thrown and return the response string. * /* w w w . j a v a2s . co m*/ * @param hr * @return * @throws SkytapException * @throws IOException * @throws ParseException */ public static String executeHttpRequest(HttpRequestBase hr) throws SkytapException { boolean retryHttpRequest = true; int retryCount = 1; String responseString = ""; while (retryHttpRequest == true) { HttpClient httpclient = new DefaultHttpClient(); // // Set timeouts for httpclient requests to 60 seconds // HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 60000); HttpConnectionParams.setSoTimeout(httpclient.getParams(), 60000); // responseString = ""; HttpResponse response = null; try { Date myDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss"); String myDateString = sdf.format(myDate); JenkinsLogger.log(myDateString + "\n" + "Executing Request: " + hr.getRequestLine()); response = httpclient.execute(hr); String responseStatusLine = response.getStatusLine().toString(); if (responseStatusLine.contains("423 Locked")) { retryCount = retryCount + 1; if (retryCount > 5) { retryHttpRequest = false; JenkinsLogger.error("Object busy too long - giving up."); } else { JenkinsLogger.log("Object busy - Retrying..."); try { Thread.sleep(15000); } catch (InterruptedException e1) { JenkinsLogger.error(e1.getMessage()); } } } else if (responseStatusLine.contains("409 Conflict")) { throw new SkytapException(responseStatusLine); } else { JenkinsLogger.log(response.getStatusLine().toString()); HttpEntity entity = response.getEntity(); responseString = EntityUtils.toString(entity, "UTF-8"); retryHttpRequest = false; } } catch (HttpResponseException e) { retryHttpRequest = false; JenkinsLogger.error("HTTP Response Code: " + e.getStatusCode()); } catch (ParseException e) { retryHttpRequest = false; JenkinsLogger.error(e.getMessage()); } catch (InterruptedIOException e) { Date myDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss"); String myDateString = sdf.format(myDate); retryCount = retryCount + 1; if (retryCount > 5) { retryHttpRequest = false; JenkinsLogger.error("API Timeout - giving up. " + e.getMessage()); } else { JenkinsLogger.log(myDateString + "\n" + e.getMessage() + "\n" + "API Timeout - Retrying..."); } } catch (IOException e) { retryHttpRequest = false; JenkinsLogger.error(e.getMessage()); } finally { if (response != null) { // response will be null if this is a timeout retry HttpEntity entity = response.getEntity(); try { responseString = EntityUtils.toString(entity, "UTF-8"); } catch (IOException e) { // JenkinsLogger.error(e.getMessage()); } } httpclient.getConnectionManager().shutdown(); } } return responseString; }
From source file:org.jenkinsci.plugins.stashNotifier.StashNotifier.java
/** * Returns the HttpClient through which the REST call is made. Uses an * unsafe TrustStrategy in case the user specified a HTTPS URL and * set the ignoreUnverifiedSSLPeer flag. * //from w w w. j av a 2 s . c om * @param logger the logger to log messages to * @return the HttpClient */ private HttpClient getHttpClient(PrintStream logger) { HttpClient client = null; boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer; DescriptorImpl descriptor = getDescriptor(); if (!ignoreUnverifiedSSL) { ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl(); } if (getStashServerBaseUrl().startsWith("https") && ignoreUnverifiedSSL) { // add unsafe trust manager to avoid thrown // SSLPeerUnverifiedException try { TrustStrategy easyStrategy = new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; SSLSocketFactory sslSocketFactory = new SSLSocketFactory(easyStrategy); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", 443, sslSocketFactory)); ClientConnectionManager connectionManager = new SingleClientConnManager(schemeRegistry); client = new DefaultHttpClient(connectionManager); } catch (NoSuchAlgorithmException nsae) { logger.println("Couldn't establish SSL context:"); nsae.printStackTrace(logger); } catch (KeyManagementException kme) { logger.println("Couldn't initialize SSL context:"); kme.printStackTrace(logger); } catch (KeyStoreException kse) { logger.println("Couldn't initialize SSL context:"); kse.printStackTrace(logger); } catch (UnrecoverableKeyException uke) { logger.println("Couldn't initialize SSL context:"); uke.printStackTrace(logger); } finally { if (client == null) { logger.println("Trying with safe trust manager, instead!"); client = new DefaultHttpClient(); } } } else { client = new DefaultHttpClient(); } ProxyConfiguration proxy = Jenkins.getInstance().proxy; if (proxy != null && !proxy.name.isEmpty() && !proxy.name.startsWith("http")) { SchemeRegistry schemeRegistry = client.getConnectionManager().getSchemeRegistry(); schemeRegistry.register(new Scheme("http", proxy.port, new PlainSocketFactory())); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxy.name, proxy.port)); } return client; }
From source file:org.madsonic.ajax.CoverArtService.java
private void saveCoverArt(String path, String url, boolean isArtist) throws Exception { InputStream input = null;/* www .j a v a2 s .c o m*/ OutputStream output = null; HttpClient client = new DefaultHttpClient(); try { HttpConnectionParams.setConnectionTimeout(client.getParams(), 20 * 1000); // 20 seconds HttpConnectionParams.setSoTimeout(client.getParams(), 20 * 1000); // 20 seconds HttpGet method = new HttpGet(url); HttpResponse response = client.execute(method); input = response.getEntity().getContent(); // Attempt to resolve proper suffix. String suffix = "jpg"; if (url.toLowerCase().endsWith(".gif")) { suffix = "gif"; } else if (url.toLowerCase().endsWith(".png")) { suffix = "png"; } String coverName = "cover."; if (isArtist == true) { coverName = "artist."; } // Check permissions. File newCoverFile = new File(path, coverName + suffix); if (!securityService.isWriteAllowed(newCoverFile)) { throw new Exception("Permission denied: " + StringUtil.toHtml(newCoverFile.getPath())); } // If file exists, create a backup. backup(newCoverFile, new File(path, "cover.backup." + suffix)); // Write file. output = new FileOutputStream(newCoverFile); IOUtils.copy(input, output); MediaFile dir = mediaFileService.getMediaFile(path); // Refresh database. mediaFileService.refreshMediaFile(dir); dir = mediaFileService.getMediaFile(dir.getId()); // Rename existing cover file if new cover file is not the preferred. try { File coverFile = mediaFileService.getCoverArt(dir); if (coverFile != null && !isMediaFile(coverFile)) { if (!newCoverFile.equals(coverFile)) { coverFile.renameTo(new File(coverFile.getCanonicalPath() + ".old")); LOG.info("Renamed old image file " + coverFile); // Must refresh again. mediaFileService.refreshMediaFile(dir); } } } catch (Exception x) { LOG.warn("Failed to rename existing cover file.", x); } } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); client.getConnectionManager().shutdown(); } }
From source file:org.madsonic.service.LastFMService.java
private void saveCoverArt(String path, String url, boolean isArtist) throws Exception { InputStream input = null;//from w w w .ja v a2 s .c om HttpClient client = new DefaultHttpClient(); try { HttpConnectionParams.setConnectionTimeout(client.getParams(), 20 * 1000); // 20 seconds HttpConnectionParams.setSoTimeout(client.getParams(), 20 * 1000); // 20 seconds HttpGet method = new HttpGet(url); org.apache.http.HttpResponse response = client.execute(method); input = response.getEntity().getContent(); // Attempt to resolve proper suffix. String suffix = "jpg"; if (url.toLowerCase().endsWith(".gif")) { suffix = "gif"; } else if (url.toLowerCase().endsWith(".png")) { suffix = "png"; } String coverName = "cover."; if (isArtist == true) { coverName = "artist."; } // Check permissions. File newCoverFile = new File(path, coverName + suffix); if (!securityService.isWriteAllowed(newCoverFile)) { throw new Exception("Permission denied: " + StringUtil.toHtml(newCoverFile.getPath())); } // If file exists, create a backup. backup(newCoverFile, new File(path, coverName + "backup." + suffix)); // Write file. IOUtils.copy(input, new FileOutputStream(newCoverFile)); MediaFile mediaFile = mediaFileService.getMediaFile(path); // Rename existing cover file if new cover file is not the preferred. try { File coverFile = mediaFileService.getCoverArt(mediaFile); if (coverFile != null) { if (!newCoverFile.equals(coverFile)) { coverFile.renameTo(new File(coverFile.getCanonicalPath() + ".old")); LOG.info("Renamed old image file " + coverFile); } } } catch (Exception x) { LOG.warn("Failed to rename existing cover file.", x); } mediaFileService.refreshMediaFile(mediaFile); } finally { IOUtils.closeQuietly(input); client.getConnectionManager().shutdown(); } }
From source file:org.oscarehr.common.hl7.v2.oscar_to_oscar.SendingUtils.java
private static int postData(String url, byte[] encryptedBytes, byte[] encryptedSecretKey, byte[] signature, String serviceName) throws IOException { MultipartEntity multipartEntity = new MultipartEntity(); String filename = serviceName + '_' + System.currentTimeMillis() + ".hl7"; multipartEntity.addPart("importFile", new ByteArrayBody(encryptedBytes, filename)); multipartEntity.addPart("key", new StringBody( new String(Base64.encodeBase64(encryptedSecretKey), MiscUtils.DEFAULT_UTF8_ENCODING))); multipartEntity.addPart("signature", new StringBody(new String(Base64.encodeBase64(signature), MiscUtils.DEFAULT_UTF8_ENCODING))); multipartEntity.addPart("service", new StringBody(serviceName)); multipartEntity.addPart("use_http_response_code", new StringBody("true")); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(multipartEntity); HttpClient httpClient = getTrustAllHttpClient(); httpClient.getParams().setParameter("http.connection.timeout", CONNECTION_TIME_OUT); HttpResponse httpResponse = httpClient.execute(httpPost); int statusCode = httpResponse.getStatusLine().getStatusCode(); logger.debug("StatusCode:" + statusCode); return (statusCode); }
From source file:org.oscarehr.common.hl7.v2.oscar_to_oscar.SendingUtils.java
private static HttpClient getTrustAllHttpClient() { try {/*from w ww .j a v a2 s . com*/ SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManager[] temp = new TrustManager[1]; temp[0] = new CxfClientUtilsOld.TrustAllManager(); sslContext.init(null, temp, null); SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext); sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpClient httpClient = new DefaultHttpClient(); ClientConnectionManager connectionManager = httpClient.getConnectionManager(); SchemeRegistry schemeRegistry = connectionManager.getSchemeRegistry(); schemeRegistry.register(new Scheme("https", sslSocketFactory, 443)); return (new DefaultHttpClient(connectionManager, httpClient.getParams())); } catch (Exception e) { logger.error("Unexpected error", e); return (null); } }
From source file:org.wso2.carbon.apimgt.hostobjects.APIProviderHostObject.java
/** * Validate the backend by sending HTTP HEAD * * @param urlVal - backend URL/*from w ww . ja v a2 s. co m*/ * @param invalidStatusCodesRegex - Regex for the invalid status code * @return - status of HTTP HEAD Request to backend */ private static NativeObject sendHttpHEADRequest(String urlVal, String invalidStatusCodesRegex) { boolean isConnectionError = true; String response = null; NativeObject data = new NativeObject(); HttpClient client = new DefaultHttpClient(); HttpHead head = new HttpHead(urlVal); client.getParams().setParameter("http.socket.timeout", 4000); client.getParams().setParameter("http.connection.timeout", 4000); if (System.getProperty(APIConstants.HTTP_PROXY_HOST) != null && System.getProperty(APIConstants.HTTP_PROXY_PORT) != null) { if (log.isDebugEnabled()) { log.debug("Proxy configured, hence routing through configured proxy"); } String proxyHost = System.getProperty(APIConstants.HTTP_PROXY_HOST); String proxyPort = System.getProperty(APIConstants.HTTP_PROXY_PORT); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, Integer.parseInt(proxyPort))); } try { HttpResponse httpResponse = client.execute(head); String statusCode = String.valueOf(httpResponse.getStatusLine().getStatusCode()); String reasonPhrase = String.valueOf(httpResponse.getStatusLine().getReasonPhrase()); //If the endpoint doesn't match the regex which specify the invalid status code, it will return success. if (!statusCode.matches(invalidStatusCodesRegex)) { if (log.isDebugEnabled() && statusCode.equals(String.valueOf(HttpStatus.SC_METHOD_NOT_ALLOWED))) { log.debug("Endpoint doesn't support HTTP HEAD"); } response = "success"; isConnectionError = false; } else { //This forms the real backend response to be sent to the client data.put("statusCode", data, statusCode); data.put("reasonPhrase", data, reasonPhrase); response = ""; isConnectionError = false; } } catch (IOException e) { // sending a default error message. log.error("Error occurred while connecting to backend : " + urlVal + ", reason : " + e.getMessage(), e); String[] errorMsg = e.getMessage().split(": "); if (errorMsg.length > 1) { response = errorMsg[errorMsg.length - 1]; //This is to get final readable part of the error message in the exception and send to the client isConnectionError = false; } } finally { client.getConnectionManager().shutdown(); } data.put("response", data, response); data.put("isConnectionError", data, isConnectionError); return data; }