List of usage examples for org.apache.http.client HttpClient getParams
@Deprecated HttpParams getParams();
From source file:com.pari.ic.ICManager.java
private String retriveICPackageFile(ICStorageServerSettings settings, ICPackage pkg, PollJobDetails details) throws Exception { String log = null;/*www.j av a 2s .c o m*/ InputStream inStream = null; HttpClient httpclient = null; Customer customer = CustomerManager.getInstance().getCustomerById(pkg.getCustomerId()); String customerName = customer.getCustomerName(); if (settings.getConnectivityType() == ConnectivityTypeEnum.CONNECTIVITY) { // DefaultHttpClient httpclient = null; // For Standalone NCCM, send the request via Connectivity String tegHost = settings.getTegHost(); if (tegHost == null) { log = "TEG URL is not configured.... "; logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.INFO_INT, null); return null; } String tegUrl = "http://" + tegHost + "/NccmCollector/ICDownloadServlet?"; log = "URL to TEG : " + tegUrl; logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.INFO_INT, null); // Sample URL - // http://172.21.136.202:8090/NccmCollector/ICDownloadServlet?GET_IC_PACK=TRUE&PACK_ID=1234 tegUrl = tegUrl + "GET_IC_PACK=TRUE"; tegUrl = tegUrl + "&"; tegUrl = tegUrl + "PACK_ID" + "=" + pkg.getPackageId(); String request = new URL(getFullUrl(settings.getServerHost()) + "/NetworkManagerWS/getFile/forPackage/" + pkg.getPackageId() + "/" + pkg.getPackageVersion() + "/" + customerName + "/" + pkg.getInstance_name()).toString(); request = request + "&&&"; request = request + settings.getUserId(); request = request + "&&&"; request = request + settings.getPassword(); log = "Request URL package download : " + request; logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.INFO_INT, null); try { httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); tegUrl = tegUrl.replaceAll(" ", "%20"); log = "Posting request to url: " + tegUrl; logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.INFO_INT, null); HttpPost httppost = new HttpPost(tegUrl); httppost.setEntity(new StringEntity(request, null, null)); httppost.setHeader("Content-type", "text/xml"); HttpResponse response = httpclient.execute(httppost); log = "Response from HTTP Client in retriveICPackageFile : " + response.toString(); logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.INFO_INT, null); inStream = response.getEntity().getContent(); } catch (Exception e) { log = "Error while posting request to TEG... "; logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.ERROR_INT, e); } } else { try { httpclient = new DefaultHttpClient(); this.pasHttpRequestHandler.getSecuredHttpClient(httpclient); HttpGet request = new HttpGet(getFullUrl(settings.getServerHost()) + "/NetworkManagerWS/getFile/forPackage/" + pkg.getPackageId() + "/" + pkg.getPackageVersion() + "/" + customerName + "/" + pkg.getInstance_name()); ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(settings.getUserId(), settings.getPassword())); HttpResponse response = httpclient.execute(request); inStream = response.getEntity().getContent(); } catch (Exception e) { log = "Error while posting request to retrieve package... "; logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.ERROR_INT, e); } } try { if (inStream != null) { ReadableByteChannel rbc = Channels.newChannel(inStream); String filePath = ICF_UPLOAD_FOLDER + File.separatorChar + pkg.getPackageId(); File file = new File(filePath); if (!file.getParentFile().exists()) { // ensure parent folder exists file.getParentFile().mkdir(); } if (file.exists()) { file.delete(); } FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.getChannel().transferFrom(rbc, 0, 1 << 24); } finally { try { if (fos != null) { fos.close(); } } catch (Exception ignore) { log = "Error while closing FileOutputStream : "; logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.ERROR_INT, ignore); } try { inStream.close(); } catch (Exception ignore) { log = "Error while closing inStream : "; logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.ERROR_INT, ignore); } } return filePath; } } finally { if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } return null; }
From source file:org.switchyard.component.resteasy.util.ClientInvoker.java
/** * Create a RESTEasy invoker client.//from w w w.j a v a 2 s.com * * @param basePath The base path for the class * @param resourceClass The JAX-RS Resource Class * @param method The JAX-RS Resource Class's method * @param model Configuration model */ public ClientInvoker(String basePath, Class<?> resourceClass, Method method, RESTEasyBindingModel model) { Set<String> httpMethods = IsHttpMethod.getHttpMethods(method); _baseUri = createUri(basePath); if ((httpMethods == null || httpMethods.size() == 0) && method.isAnnotationPresent(Path.class) && method.getReturnType().isInterface()) { _subResourcePath = createSubResourcePath(basePath, method); } else if (httpMethods == null || httpMethods.size() != 1) { throw RestEasyMessages.MESSAGES .youMustUseAtLeastOneButNoMoreThanOneHttpMethodAnnotationOn(method.toString()); } _httpMethod = httpMethods.iterator().next(); _resourceClass = resourceClass; _method = method; try { _uri = (UriBuilder) URIBUILDER_CLASS.newInstance(); } catch (InstantiationException ie) { throw new RuntimeException(ie); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } _uri.uri(_baseUri); if (_resourceClass.isAnnotationPresent(Path.class)) { _uri.path(_resourceClass); } if (_method.isAnnotationPresent(Path.class)) { _uri.path(_method); } _providerFactory = new ResteasyProviderFactory(); boolean useBuiltins = true; // use builtin @Provider classes by default if (model.getContextParamsConfig() != null) { Map<String, String> contextParams = model.getContextParamsConfig().toMap(); // Set use builtin @Provider classes String registerBuiltins = contextParams.get(ResteasyContextParameters.RESTEASY_USE_BUILTIN_PROVIDERS); if (registerBuiltins != null) { useBuiltins = Boolean.parseBoolean(registerBuiltins); } // Register @Provider classes List<Class<?>> providerClasses = RESTEasyUtil.getProviderClasses(contextParams); if (providerClasses != null) { for (Class<?> pc : providerClasses) { _providerFactory.registerProvider(pc); } } List<ClientErrorInterceptor> interceptors = RESTEasyUtil.getClientErrorInterceptors(contextParams); if (interceptors != null) { for (ClientErrorInterceptor interceptor : interceptors) { _providerFactory.addClientErrorInterceptor(interceptor); } } } if (useBuiltins) { _providerFactory.setRegisterBuiltins(true); RegisterBuiltin.register(_providerFactory); } _extractorFactory = new DefaultEntityExtractorFactory(); _extractor = _extractorFactory.createExtractor(_method); _marshallers = ClientMarshallerFactory.createMarshallers(_resourceClass, _method, _providerFactory, null); _accepts = MediaTypeHelper.getProduces(_resourceClass, method, null); ClientInvokerInterceptorFactory.applyDefaultInterceptors(this, _providerFactory, _resourceClass, _method); // Client executor SchemeRegistry schemeRegistry = new SchemeRegistry(); int port = _baseUri.getPort(); if (_baseUri.getScheme().startsWith("https")) { if (port == -1) { port = 443; } SSLSocketFactory sslFactory = getSSLSocketFactory(model.getSSLContextConfig()); if (sslFactory == null) { sslFactory = SSLSocketFactory.getSocketFactory(); } schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, sslFactory)); } else { if (port == -1) { port = 80; } schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, PlainSocketFactory.getSocketFactory())); } PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); cm.setMaxTotal(200); cm.setDefaultMaxPerRoute(20); HttpClient httpClient = new DefaultHttpClient(cm); _executor = new ApacheHttpClient4Executor(httpClient); // register ApacheHttpClient4ExceptionMapper manually for local instance of ResteasyProviderFactory Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(ApacheHttpClient4ExceptionMapper.class, ClientExceptionMapper.class)[0]; _providerFactory.addClientExceptionMapper(new ApacheHttpClient4ExceptionMapper(), exceptionType); // Authentication settings if (model.hasAuthentication()) { // Set authentication AuthScope authScope = null; Credentials credentials = null; if (model.isBasicAuth()) { authScope = createAuthScope(model.getBasicAuthConfig().getHost(), model.getBasicAuthConfig().getPort(), model.getBasicAuthConfig().getRealm()); credentials = new UsernamePasswordCredentials(model.getBasicAuthConfig().getUser(), model.getBasicAuthConfig().getPassword()); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); authCache.put(new HttpHost(authScope.getHost(), authScope.getPort()), new BasicScheme(ChallengeState.TARGET)); BasicHttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.AUTH_CACHE, authCache); ((ApacheHttpClient4Executor) _executor).setHttpContext(context); } else { authScope = createAuthScope(model.getNtlmAuthConfig().getHost(), model.getNtlmAuthConfig().getPort(), model.getNtlmAuthConfig().getRealm()); credentials = new NTCredentials(model.getNtlmAuthConfig().getUser(), model.getNtlmAuthConfig().getPassword(), "", model.getNtlmAuthConfig().getDomain()); } ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials); } else { ProxyModel proxy = model.getProxyConfig(); if (proxy != null) { HttpHost proxyHost = null; if (proxy.getPort() != null) { proxyHost = new HttpHost(proxy.getHost(), Integer.valueOf(proxy.getPort()).intValue()); } else { proxyHost = new HttpHost(proxy.getHost(), -1); } if (proxy.getUser() != null) { AuthScope authScope = new AuthScope(proxy.getHost(), Integer.valueOf(proxy.getPort()).intValue(), AuthScope.ANY_REALM); Credentials credentials = new UsernamePasswordCredentials(proxy.getUser(), proxy.getPassword()); AuthCache authCache = new BasicAuthCache(); authCache.put(proxyHost, new BasicScheme(ChallengeState.PROXY)); ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials); BasicHttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.AUTH_CACHE, authCache); ((ApacheHttpClient4Executor) _executor).setHttpContext(context); } httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost); } } Integer timeout = model.getTimeout(); if (timeout != null) { HttpParams httpParams = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, timeout); HttpConnectionParams.setSoTimeout(httpParams, timeout); } }
From source file:net.dahanne.gallery3.client.business.G3Client.java
private HttpEntity requestToResponseEntity(String appendToGalleryUrl, List<NameValuePair> nameValuePairs, String requestMethod, File file) throws UnsupportedEncodingException, IOException, ClientProtocolException, G3GalleryException { HttpClient defaultHttpClient = new DefaultHttpClient(); HttpRequestBase httpMethod;/*from ww w . j a va 2 s . co m*/ //are we using rewritten urls ? if (this.isUsingRewrittenUrls && appendToGalleryUrl.contains(INDEX_PHP_REST)) { appendToGalleryUrl = StringUtils.remove(appendToGalleryUrl, "index.php"); } logger.debug("requestToResponseEntity , url requested : {}", galleryItemUrl + appendToGalleryUrl); if (POST.equals(requestMethod)) { httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl); httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod); if (file != null) { MultipartEntity multipartEntity = new MultipartEntity(); String string = nameValuePairs.toString(); // dirty fix to remove the enclosing entity{} String substring = string.substring(string.indexOf("{"), string.lastIndexOf("}") + 1); StringBody contentBody = new StringBody(substring, Charset.forName("UTF-8")); multipartEntity.addPart("entity", contentBody); FileBody fileBody = new FileBody(file); multipartEntity.addPart("file", fileBody); ((HttpPost) httpMethod).setEntity(multipartEntity); } else { ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs)); } } else if (PUT.equals(requestMethod)) { httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl); httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod); ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs)); } else if (DELETE.equals(requestMethod)) { httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl); httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod); //this is to avoid the HTTP 414 (length too long) error //it should only happen when getting items, index.php/rest/items?urls= // } else if(appendToGalleryUrl.length()>2000) { // String resource = appendToGalleryUrl.substring(0,appendToGalleryUrl.indexOf("?")); // String variable = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("?")+1,appendToGalleryUrl.indexOf("=")); // String value = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("=")+1); // httpMethod = new HttpPost(galleryItemUrl + resource); // httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod); // nameValuePairs.add(new BasicNameValuePair(variable, value)); // ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity( // nameValuePairs)); } else { httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl); } if (existingApiKey != null) { httpMethod.setHeader(X_GALLERY_REQUEST_KEY, existingApiKey); } //adding the userAgent to the request httpMethod.setHeader(USER_AGENT, userAgent); HttpResponse response = null; String[] patternsArray = new String[3]; patternsArray[0] = "EEE, dd MMM-yyyy-HH:mm:ss z"; patternsArray[1] = "EEE, dd MMM yyyy HH:mm:ss z"; patternsArray[2] = "EEE, dd-MMM-yyyy HH:mm:ss z"; try { // be extremely careful here, android httpclient needs it to be // an // array of string, not an arraylist defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsArray); response = defaultHttpClient.execute(httpMethod); } catch (ClassCastException e) { List<String> patternsList = Arrays.asList(patternsArray); defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsList); response = defaultHttpClient.execute(httpMethod); } int responseStatusCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = null; if (response.getEntity() != null) { responseEntity = response.getEntity(); } switch (responseStatusCode) { case HttpURLConnection.HTTP_CREATED: break; case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_MOVED_TEMP: //the gallery is using rewritten urls, let's remember it and re hit the server this.isUsingRewrittenUrls = true; responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file); break; case HttpURLConnection.HTTP_BAD_REQUEST: throw new G3BadRequestException(); case HttpURLConnection.HTTP_FORBIDDEN: //for some reasons, the gallery may respond with 403 when trying to log in with the wrong url if (appendToGalleryUrl.contains(INDEX_PHP_REST)) { this.isUsingRewrittenUrls = true; responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file); break; } throw new G3ForbiddenException(); case HttpURLConnection.HTTP_NOT_FOUND: throw new G3ItemNotFoundException(); default: throw new G3GalleryException("HTTP code " + responseStatusCode); } return responseEntity; }
From source file:com.nextgis.maplibui.services.HTTPLoader.java
protected String signIn() throws IOException { //1. fix url/*from w ww .j a v a2 s . c o m*/ String url; if (mUrl.startsWith("http")) url = mUrl + "/login"; else url = "http://" + mUrl + "/login"; HttpPost httppost = new HttpPost(url); List<NameValuePair> nameValuePairs = new ArrayList<>(2); nameValuePairs.add(new BasicNameValuePair("login", mLogin)); nameValuePairs.add(new BasicNameValuePair("password", mPassword)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, APP_USER_AGENT); httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT_CONNECTION); httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT_SOKET); httpclient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE); HttpResponse response = httpclient.execute(httppost); //2 get cookie Header head = response.getFirstHeader("Set-Cookie"); if (head == null) return null; return head.getValue(); }
From source file:mobisocial.musubi.BootstrapActivity.java
Integer getRequiredVersion() { if (UsageMetrics.CHIRP_VERSIONING_ENDPOINT == null) { return null; }//from w ww .j av a2 s . c o m HttpClient http = new CertifiedHttpClient(this); HttpParams params = http.getParams(); HttpProtocolParams.setUseExpectContinue(params, false); HttpConnectionParams.setConnectionTimeout(params, 6000); HttpConnectionParams.setSoTimeout(params, 6000); HttpGet get = new HttpGet(UsageMetrics.CHIRP_VERSIONING_ENDPOINT); try { HttpResponse response = http.execute(get); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line; while ((line = in.readLine()) != null) { sb.append(line); } in.close(); JSONObject json = new JSONObject(sb.toString()); return json.getInt("required"); } catch (IOException e) { Log.e(TAG, "Error getting versioning info", e); return null; } catch (JSONException e) { Log.e(TAG, "Bad versioning format", e); return null; } }
From source file:net.sourceforge.subsonic.ajax.CoverArtService.java
private void saveCoverArt(String path, String url) throws Exception { InputStream input = null;/*from w w w . j a va2s . c o m*/ 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"; } // Check permissions. File newCoverFile = new File(path, "folder." + 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, "folder.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.apache.camel.component.http4.HttpEndpoint.java
/** * Factory method to create a new {@link HttpClient} instance * <p/>//from w w w . j a v a 2s .c o m * Producers and consumers should use the {@link #getHttpClient()} method instead. */ protected HttpClient createHttpClient() { ObjectHelper.notNull(clientParams, "clientParams"); ObjectHelper.notNull(clientConnectionManager, "httpConnectionManager"); HttpClient answer = new DefaultHttpClient(clientConnectionManager, getClientParams()); // configure http proxy from camelContext if (ObjectHelper.isNotEmpty(getCamelContext().getProperties().get("http.proxyHost")) && ObjectHelper.isNotEmpty(getCamelContext().getProperties().get("http.proxyPort"))) { String host = getCamelContext().getProperties().get("http.proxyHost"); int port = Integer.parseInt(getCamelContext().getProperties().get("http.proxyPort")); if (LOG.isDebugEnabled()) { LOG.debug( "CamelContext properties http.proxyHost and http.proxyPort detected. Using http proxy host: " + host + " port: " + port); } HttpHost proxy = new HttpHost(host, port); answer.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } HttpClientConfigurer configurer = getHttpClientConfigurer(); if (configurer != null) { configurer.configureHttpClient(answer); } if (LOG.isDebugEnabled()) { LOG.debug("Created HttpClient " + answer); } return answer; }
From source file:org.bigmouth.nvwa.network.http.HttpClientHelper.java
@SuppressWarnings("deprecation") private static HttpClient getHttpClient(File keystore, char[] pwd, ClientConnectionManager ccm, int port, int timeout) throws Exception { SchemeRegistry sr = ccm.getSchemeRegistry(); KeyStore truststore = KeyStore.getInstance(KeyStore.getDefaultType()); truststore.load(new FileInputStream(keystore), pwd); SSLSocketFactory socketFactory = new SSLSocketFactory(truststore); socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); sr.register(new Scheme("https", port, socketFactory)); HttpClient httpClient = new DefaultHttpClient(ccm); 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.bigmouth.nvwa.network.http.HttpClientHelper.java
private static HttpClient getHttpClient(SSLContext ctx, ClientConnectionManager ccm, int port, int timeout) { SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(// ww w . j a v a2s. c om new Scheme("https", port, new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))); HttpClient httpClient = new DefaultHttpClient(ccm); httpClient.getParams().setParameter(CoreConnectionPNames.SO_KEEPALIVE, true); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); return httpClient; }