List of usage examples for org.apache.commons.httpclient.params HttpClientParams HttpClientParams
public HttpClientParams()
From source file:com.chengfeng.ne.basicInterface.service.impl.BasicInterfaceServiceImpl.java
/** * ??//from w ww.j a va2s .c om */ @Override public String sendRequest(String data, String url) throws ServiceException { final List<NameValuePair> nameValueList = new ArrayList<NameValuePair>(); // ?? nameValueList.add(new NameValuePair("param", data)); HttpClientParams httpClientParams = new HttpClientParams(); httpClientParams.setConnectionManagerTimeout(1000); final HttpClient httpClient = new HttpClient(httpClientParams, new SimpleHttpConnectionManager(true)); final PostMethod postMethod = new PostMethod(url); postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); postMethod.setRequestBody(nameValueList.toArray(new NameValuePair[nameValueList.size()])); postMethod.addRequestHeader("Connection", "close"); String result = ""; try { try { httpClient.executeMethod(postMethod); result = postMethod.getResponseBodyAsString(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String str = result; log.info("" + str); return str; } finally { postMethod.releaseConnection(); } }
From source file:io.hops.hopsworks.api.admin.YarnUIProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { if (servletRequest.getUserPrincipal() == null) { servletResponse.sendError(403, "User is not logged in"); return;/*from w ww . j ava2s.com*/ } if (!servletRequest.isUserInRole("HOPS_ADMIN")) { servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(), "You don't have the access right for this service"); return; } if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) { servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); } if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) { servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); } // Make the Request // note: we won't transfer the protocol version because I'm not // sure it would truly be compatible String proxyRequestUri = rewriteUrlFromRequest(servletRequest); try { // Execute the request HttpClientParams params = new HttpClientParams(); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); HttpClient client = new HttpClient(params); HostConfiguration config = new HostConfiguration(); InetAddress localAddress = InetAddress.getLocalHost(); config.setLocalAddress(localAddress); String method = servletRequest.getMethod(); HttpMethod m; if (method.equalsIgnoreCase("PUT")) { m = new PutMethod(proxyRequestUri); RequestEntity requestEntity = new InputStreamRequestEntity(servletRequest.getInputStream(), servletRequest.getContentType()); ((PutMethod) m).setRequestEntity(requestEntity); } else { m = new GetMethod(proxyRequestUri); } Enumeration<String> names = servletRequest.getHeaderNames(); while (names.hasMoreElements()) { String headerName = names.nextElement(); String value = servletRequest.getHeader(headerName); if (PASS_THROUGH_HEADERS.contains(headerName)) { //yarn does not send back the js if encoding is not accepted //but we don't want to accept encoding for the html because we //need to be able to parse it if (headerName.equalsIgnoreCase("accept-encoding") && (servletRequest.getPathInfo() == null || !servletRequest.getPathInfo().contains(".js"))) { continue; } else { m.setRequestHeader(headerName, value); } } } String user = servletRequest.getRemoteUser(); if (user != null && !user.isEmpty()) { m.setRequestHeader("Cookie", "proxy-user" + "=" + URLEncoder.encode(user, "ASCII")); } client.executeMethod(config, m); // Process the response int statusCode = m.getStatusCode(); // Pass the response code. This method with the "reason phrase" is //deprecated but it's the only way to pass the reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, m.getStatusLine().getReasonPhrase()); copyResponseHeaders(m, servletRequest, servletResponse); // Send the content to the client copyResponseEntity(m, servletResponse); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } if (e instanceof ServletException) { throw (ServletException) e; } //noinspection ConstantConditions if (e instanceof IOException) { throw (IOException) e; } throw new RuntimeException(e); } }
From source file:com.mirth.connect.client.core.UpdateClient.java
public void registerUser(User user) throws ClientException { HttpClientParams httpClientParams = new HttpClientParams(); HttpConnectionManager httpConnectionManager = new SimpleHttpConnectionManager(); httpClientParams.setSoTimeout(10 * 1000); httpConnectionManager.getParams().setConnectionTimeout(10 * 1000); httpConnectionManager.getParams().setSoTimeout(10 * 1000); HttpClient httpClient = new HttpClient(httpClientParams, httpConnectionManager); PostMethod post = new PostMethod(client.getUpdateSettings().getUpdateUrl() + URL_REGISTRATION); NameValuePair[] params = { new NameValuePair("serverId", client.getServerId()), new NameValuePair("version", client.getVersion()), new NameValuePair("user", serializer.toXML(user)) }; post.setRequestBody(params);//from w ww .j av a 2s . c o m try { int statusCode = httpClient.executeMethod(post); if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_MOVED_TEMPORARILY)) { throw new Exception("Failed to connect to update server: " + post.getStatusLine()); } } catch (Exception e) { throw new ClientException(e); } finally { post.releaseConnection(); } }
From source file:edu.utah.further.core.ws.HttpClientTemplate.java
/** * Private {@link HttpClient} initialization. *///from w w w .j a v a 2 s . c o m @PostConstruct private final void afterPropertiesSet() { // Client is higher in the hierarchy than manager so set the parameters here final HttpClientParams clientParams = new HttpClientParams(); clientParams.setConnectionManagerClass(connectionManager.getClass()); clientParams.setConnectionManagerTimeout(connectionTimeout); clientParams.setSoTimeout(readTimeout); clientParams.setParameter("http.connection.timeout", new Integer(connectionTimeout)); // A retry handler for when a connection fails clientParams.setParameter(HttpMethodParams.RETRY_HANDLER, new HttpMethodRetryHandler() { @Override public boolean retryMethod(final HttpMethod method, final IOException exception, final int executionCount) { if (executionCount >= retryCount) { // Do not retry if over max retry count return false; } if (instanceOf(exception, NoHttpResponseException.class)) { // Retry if the server dropped connection on us return true; } if (instanceOf(exception, SocketException.class)) { // Retry if the server reset connection on us return true; } if (instanceOf(exception, SocketTimeoutException.class)) { // Retry if the read timed out return true; } if (!method.isRequestSent()) { // Retry if the request has not been sent fully or // if it's OK to retry methods that have been sent return true; } // otherwise do not retry return false; } }); httpClient.setParams(clientParams); final HttpConnectionManagerParams connectionManagerParams = connectionManager.getParams(); connectionManagerParams.setDefaultMaxConnectionsPerHost(maxConnectionsPerHost); connectionManager.setParams(connectionManagerParams); }
From source file:com.yahoo.flowetl.services.http.BaseHttpGenerator.java
/** * Gets the http client params.//ww w. j a v a2s.c om * * @return the client params */ protected HttpClientParams getClientParams(HttpParams in) { HttpClientParams out = new HttpClientParams(); out.setSoTimeout(in.socketTO); out.setContentCharset(DEF_CHARSET); out.setUriCharset(DEF_CHARSET); out.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); return out; }
From source file:io.hops.hopsworks.api.admin.HDFSUIProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { if (servletRequest.getUserPrincipal() == null) { servletResponse.sendError(403, "User is not logged in"); return;/*from w w w .j a v a2 s. c o m*/ } if (!servletRequest.isUserInRole("HOPS_ADMIN")) { servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(), "You don't have the access right for this service"); return; } if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) { servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); } if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) { servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); } // Make the Request // note: we won't transfer the protocol version because I'm not // sure it would truly be compatible String proxyRequestUri = rewriteUrlFromRequest(servletRequest); try { String[] targetHost_port = settings.getHDFSWebUIAddress().split(":"); File keyStore = new File(baseHadoopClientsService.getSuperKeystorePath()); File trustStore = new File(baseHadoopClientsService.getSuperTrustStorePath()); // Assume that KeyStore password and Key password are the same Protocol httpsProto = new Protocol("https", new CustomSSLProtocolSocketFactory(keyStore, baseHadoopClientsService.getSuperKeystorePassword(), baseHadoopClientsService.getSuperKeystorePassword(), trustStore, baseHadoopClientsService.getSuperTrustStorePassword()), Integer.parseInt(targetHost_port[1])); Protocol.registerProtocol("https", httpsProto); // Execute the request HttpClientParams params = new HttpClientParams(); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); HttpClient client = new HttpClient(params); HostConfiguration config = new HostConfiguration(); InetAddress localAddress = InetAddress.getLocalHost(); config.setLocalAddress(localAddress); HttpMethod m = new GetMethod(proxyRequestUri); Enumeration<String> names = servletRequest.getHeaderNames(); while (names.hasMoreElements()) { String headerName = names.nextElement(); String value = servletRequest.getHeader(headerName); if (PASS_THROUGH_HEADERS.contains(headerName)) { //hdfs does not send back the js if encoding is not accepted //but we don't want to accept encoding for the html because we //need to be able to parse it if (headerName.equalsIgnoreCase("accept-encoding") && (servletRequest.getPathInfo() == null || !servletRequest.getPathInfo().contains(".js"))) { continue; } else { m.setRequestHeader(headerName, value); } } } String user = servletRequest.getRemoteUser(); if (user != null && !user.isEmpty()) { m.setRequestHeader("Cookie", "proxy-user" + "=" + URLEncoder.encode(user, "ASCII")); } client.executeMethod(config, m); // Process the response int statusCode = m.getStatusCode(); // Pass the response code. This method with the "reason phrase" is //deprecated but it's the only way to pass the reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, m.getStatusLine().getReasonPhrase()); copyResponseHeaders(m, servletRequest, servletResponse); // Send the content to the client copyResponseEntity(m, servletResponse); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } if (e instanceof ServletException) { throw (ServletException) e; } //noinspection ConstantConditions if (e instanceof IOException) { throw (IOException) e; } throw new RuntimeException(e); } }
From source file:fr.cls.atoll.motu.processor.wps.framework.WPSUtils.java
/** * Performs an HTTP-Get request and provides typed access to the response. * // ww w . j av a 2 s .c o m * @param <T> * @param worker * @param url * @param postBody * @param headers * @return some object from the url * @throws HttpException * @throws IOException * @throws MotuException */ public static <T> T post(Worker<T> worker, String url, InputStream postBody, Map<String, String> headers) throws HttpException, IOException, MotuException { if (LOG.isDebugEnabled()) { LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - start"); } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copy(postBody, out); } finally { IOUtils.closeQuietly(out); } InputStream postBodyCloned = new ByteArrayInputStream(out.toString().getBytes()); MultiThreadedHttpConnectionManager connectionManager = HttpUtil.createConnectionManager(); HttpClientCAS client = new HttpClientCAS(connectionManager); HttpClientParams clientParams = new HttpClientParams(); //clientParams.setParameter("http.protocol.allow-circular-redirects", true); //HttpClientParams.ALLOW_CIRCULAR_REDIRECTS client.setParams(clientParams); PostMethod post = new PostMethod(url); post.getParams().setCookiePolicy(CookiePolicy.RFC_2109); InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(postBody); post.setRequestEntity(inputStreamRequestEntity); for (String key : headers.keySet()) { post.setRequestHeader(key, headers.get(key)); } String query = post.getQueryString(); // Check redirection // DONT USE post.setFollowRedirects(true); see http://hc.apache.org/httpclient-3.x/redirects.html int httpReturnCode = client.executeMethod(post); if (LOG.isDebugEnabled()) { String msg = String.format("Executing the query:\n==> http code: '%d':\n==> url: '%s'\n==> body:\n'%s'", httpReturnCode, url, query); LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end - " + msg); } if (httpReturnCode == 302) { post.releaseConnection(); String redirectLocation = null; Header locationHeader = post.getResponseHeader("location"); if (locationHeader != null) { redirectLocation = locationHeader.getValue(); if (!WPSUtils.isNullOrEmpty(redirectLocation)) { if (LOG.isDebugEnabled()) { String msg = String.format("Query is redirected to url: '%s'", redirectLocation); LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end - " + msg); } post = new PostMethod(url); post.setRequestEntity(new InputStreamRequestEntity(postBodyCloned)); // Recrire un nouveau InputStream for (String key : headers.keySet()) { post.setRequestHeader(key, headers.get(key)); } clientParams.setBooleanParameter(HttpClientCAS.ADD_CAS_TICKET_PARAM, false); httpReturnCode = client.executeMethod(post); clientParams.setBooleanParameter(HttpClientCAS.ADD_CAS_TICKET_PARAM, true); if (LOG.isDebugEnabled()) { String msg = String.format( "Executing the query:\n==> http code: '%d':\n==> url: '%s'\n==> body:\n'%s'", httpReturnCode, url, query); LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end - " + msg); } } } } T returnValue = worker.work(post.getResponseBodyAsStream()); if (httpReturnCode >= 400) { if (LOG.isDebugEnabled()) { LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end"); } String msg = String.format( "Error while executing the query:\n==> http code: '%d':\n==> url: '%s'\n==> body:\n'%s'", httpReturnCode, url, query); throw new MotuException(msg); } if (LOG.isDebugEnabled()) { LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end"); } return returnValue; }
From source file:ac.elements.io.Signature.java
/** * Configure HttpClient with set of defaults as well as configuration from * AmazonEC2Config instance./*from w w w.j a v a2 s. c om*/ * * @return the http client */ private static HttpClient configureHttpClient() { /* Set http client parameters */ HttpClientParams httpClientParams = new HttpClientParams(); httpClientParams.setParameter(HttpMethodParams.USER_AGENT, USER_AGENT); httpClientParams.setParameter(HttpMethodParams.RETRY_HANDLER, new HttpMethodRetryHandler() { public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) { if (executionCount > MAX_RETRY_ERROR) { log.warn("Maximum Number of Retry attempts " + "reached, will not retry"); return false; } log.warn("Retrying request. Attempt " + executionCount); if (exception instanceof NoHttpResponseException) { log.warn("Retrying on NoHttpResponseException"); return true; } if (exception instanceof InterruptedIOException) { log.warn("Will not retry on InterruptedIOException", exception); return false; } if (exception instanceof UnknownHostException) { log.warn("Will not retry on UnknownHostException", exception); return false; } if (!method.isRequestSent()) { log.warn("Retrying on failed sent request"); return true; } return false; } }); /* Set host configuration */ HostConfiguration hostConfiguration = new HostConfiguration(); /* Set connection manager parameters */ HttpConnectionManagerParams connectionManagerParams = new HttpConnectionManagerParams(); connectionManagerParams.setConnectionTimeout(50000); connectionManagerParams.setSoTimeout(50000); connectionManagerParams.setStaleCheckingEnabled(true); connectionManagerParams.setTcpNoDelay(true); connectionManagerParams.setMaxTotalConnections(MAX_CONNECTIONS); connectionManagerParams.setMaxConnectionsPerHost(hostConfiguration, MAX_CONNECTIONS); /* Set connection manager */ MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.setParams(connectionManagerParams); /* Set http client */ httpClient = new HttpClient(httpClientParams, connectionManager); /* Set proxy if configured */ // if (config.isSetProxyHost() && config.isSetProxyPort()) { // log.info("Configuring Proxy. Proxy Host: " + config.getProxyHost() + // "Proxy Port: " + config.getProxyPort() ); // hostConfiguration.setProxy(config.getProxyHost(), // config.getProxyPort()); // if (config.isSetProxyUsername() && config.isSetProxyPassword()) { // httpClient.getState().setProxyCredentials (new AuthScope( // config.getProxyHost(), // config.getProxyPort()), // new UsernamePasswordCredentials( // config.getProxyUsername(), // config.getProxyPassword())); // // } // } httpClient.setHostConfiguration(hostConfiguration); return httpClient; }
From source file:com.mirth.connect.client.core.UpdateClient.java
private List<UpdateInfo> getUpdatesFromUri(ServerInfo serverInfo) throws Exception { HttpClientParams httpClientParams = new HttpClientParams(); HttpConnectionManager httpConnectionManager = new SimpleHttpConnectionManager(); httpClientParams.setSoTimeout(10 * 1000); httpConnectionManager.getParams().setConnectionTimeout(10 * 1000); httpConnectionManager.getParams().setSoTimeout(10 * 1000); HttpClient httpClient = new HttpClient(httpClientParams, httpConnectionManager); PostMethod post = new PostMethod(client.getUpdateSettings().getUpdateUrl() + URL_UPDATES); NameValuePair[] params = { new NameValuePair("serverInfo", serializer.toXML(serverInfo)) }; post.setRequestBody(params);//w w w .j a v a2s.co m try { int statusCode = httpClient.executeMethod(post); if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_MOVED_TEMPORARILY)) { throw new Exception("Failed to connect to update server: " + post.getStatusLine()); } BufferedReader reader = new BufferedReader( new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet())); StringBuilder result = new StringBuilder(); String input = new String(); while ((input = reader.readLine()) != null) { result.append(input); result.append('\n'); } return (List<UpdateInfo>) serializer.fromXML(result.toString()); } catch (Exception e) { throw e; } finally { post.releaseConnection(); } }
From source file:com.ning.http.client.providers.apache.ApacheAsyncHttpProvider.java
public ApacheAsyncHttpProvider(AsyncHttpClientConfig config) { this.config = config; connectionManager = new MultiThreadedHttpConnectionManager(); params = new HttpClientParams(); params.setParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, Boolean.TRUE); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); AsyncHttpProviderConfig<?, ?> providerConfig = config.getAsyncHttpProviderConfig(); if (providerConfig != null && ApacheAsyncHttpProvider.class.isAssignableFrom(providerConfig.getClass())) { configure(ApacheAsyncHttpProviderConfig.class.cast(providerConfig)); }//w w w . j ava 2 s.c o m }