List of usage examples for org.apache.commons.httpclient DefaultHttpMethodRetryHandler DefaultHttpMethodRetryHandler
public DefaultHttpMethodRetryHandler(int paramInt, boolean paramBoolean)
From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java
private HttpResponse executeWithTimeout(final HttpMethodBase httpMethod, int timeoutMillis) { client.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler(0, false)); ExecutorService service = Executors.newSingleThreadExecutor(); Future<HttpResponse> future = service.submit(new Callable<HttpResponse>() { @Override/*from ww w . j av a2 s. com*/ public HttpResponse call() throws IOException { return execute(httpMethod); } }); try { return future.get(timeoutMillis, TimeUnit.MILLISECONDS); } catch (Exception e) { String uriInfo = ""; try { uriInfo = " for " + httpMethod.getURI(); } catch (Exception ie) { } LOG.warn("Http connection thread was interrupted or has timed out" + uriInfo, e); return new HttpResponse(HttpStatus.SC_REQUEST_TIMEOUT, "Request Timeout", null); } finally { service.shutdownNow(); } }
From source file:edu.uci.ics.asterix.test.aql.TestsUtils.java
public static void executeDDL(String str) throws Exception { final String url = "http://localhost:19002/ddl"; // Create a method instance. PostMethod method = new PostMethod(url); method.setRequestEntity(new StringRequestEntity(str)); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Execute the method. executeHttpMethod(method);/* w w w.ja v a 2 s.co m*/ }
From source file:com.legstar.http.client.CicsHttp.java
/** * Create a reusable HTTP Client with a set of parameters that match * the remote CICS Server characteristics. At this stage, the HTTPClient is not * associated with a state and a method yet. * @param cicsHttpEndpoint the connection configuration * @return the new HTTP Client/*from ww w. j a v a2 s . co m*/ */ protected HttpClient createHttpClient(final CicsHttpEndpoint cicsHttpEndpoint) { if (_log.isDebugEnabled()) { _log.debug("enter createHttpClient()"); } HttpClientParams params = new HttpClientParams(); /* Consider that if server is failing to respond, we should never retry. * A system such as CICS should always be responsive unless something * bad is happening in which case, retry makes things worse. */ DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false); params.setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler); /* Preemptive authentication forces the first HTTP payload to hold * credentials. This bypasses the inefficient default mechanism that * expects a 401 reply on the first request and then re-issues the same * request again with credentials.*/ params.setAuthenticationPreemptive(true); /* Set the receive time out. */ params.setSoTimeout(cicsHttpEndpoint.getReceiveTimeout()); /* Tell the connection manager how long we are prepared to wait * for a connection. */ params.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, cicsHttpEndpoint.getConnectTimeout()); /* Disable Nagle algorithm */ params.setBooleanParameter(HttpConnectionParams.TCP_NODELAY, true); HttpClient httpClient = new HttpClient(params); httpClient.setHostConfiguration(createHostConfiguration(cicsHttpEndpoint)); return httpClient; }
From source file:com.celamanzi.liferay.portlets.rails286.OnlineClient.java
/** Prepares method headers. * * Modifies the given method by inserting, when defined: * - Referer//from w w w.j a v a 2 s . c o m * - Accept-Language * * @since 0.8.0 */ protected HttpMethod prepareMethodHeaders(HttpMethod method) { // Insert the HTTP Referer if (httpReferer != null) { log.debug("HTTP referer: " + httpReferer.toString()); method.setRequestHeader("Referer", httpReferer.toString()); } else { //log.debug("HTTP referer is null"); } // Insert the Locale if (locale != null) { log.debug("Request's locale language: " + locale.toString()); method.setRequestHeader("Accept-Language", locale.toString()); } else { //log.debug("Locale is null"); } //Correct the charset problem method.getParams().setContentCharset("UTF-8"); // Provide custom retry handler method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(retries, false)); return method; }
From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java
private GetMethod createGetMethod(String resource) { GetMethod method = new GetMethod(resource); // Provide custom retry handler method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(NUMBER_OF_RETRIES, false)); return method; }
From source file:edu.uci.ics.pregelix.example.util.TestExecutor.java
public InputStream executeAnyAQLAsync(String str, boolean defer, OutputFormat fmt, String url) throws Exception { // Create a method instance. PostMethod method = new PostMethod(url); if (defer) {/*from w w w . j a va 2s .co m*/ method.setQueryString(new NameValuePair[] { new NameValuePair("mode", "asynchronous-deferred") }); } else { method.setQueryString(new NameValuePair[] { new NameValuePair("mode", "asynchronous") }); } method.setRequestEntity(new StringRequestEntity(str)); method.setRequestHeader("Accept", fmt.mimeType()); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); executeHttpMethod(method); InputStream resultStream = method.getResponseBodyAsStream(); String theHandle = IOUtils.toString(resultStream, "UTF-8"); // take the handle and parse it so results can be retrieved InputStream handleResult = getHandleResult(theHandle, fmt); return handleResult; }
From source file:es.juntadeandalucia.mapea.proxy.ProxyRedirect.java
/*************************************************************************** * Process the HTTP Post request/*w w w . java2s . co m*/ ***************************************************************************/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { boolean checkedContent = false; boolean legend = false; String strErrorMessage = ""; String serverUrl = request.getParameter("url"); log.info("POST param serverUrl: " + serverUrl); if (serverUrl.startsWith("legend")) { serverUrl = serverUrl.replace("legend", ""); serverUrl = serverUrl.replace("?", "&"); serverUrl = serverUrl.replaceFirst("&", "?"); legend = true; } serverUrl = checkTypeRequest(serverUrl); // log.info("serverUrl ckecked: " + serverUrl); if (!serverUrl.equals("ERROR")) { if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) { PostMethod httppost = null; try { if (log.isDebugEnabled()) { Enumeration<?> e = request.getHeaderNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String value = request.getHeader(name); log.debug("request header:" + name + ":" + value); } } HttpClient client = new HttpClient(); httppost = new PostMethod(serverUrl); // PATH httppost.setDoAuthentication(false); httppost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // FIN_PATH // PATH_MAPEAEDITA_SECURITY - AP // PATCH_TICKET_MJM-20112405-POST String authorizationValue = request.getHeader(AUTHORIZATION); // ADD_SECURITY_20091210 if (authorizationValue == null) { // The 'Authorization' header must be in this form -> // Authorization: Basic <encodedLogin> // 'encodedLogin' is a string in the form 'user:pass' // that has been encoded by way of the Base64 algorithm. // More info on this can be found at // http://en.wikipedia.org/wiki/Basic_access_authentication String user = (String) request.getSession().getAttribute("user"); String pass = (String) request.getSession().getAttribute("pass"); if (user != null && pass != null) { String userAndPass = user + ":" + pass; String encodedLogin = new String( org.apache.commons.codec.binary.Base64.encodeBase64(userAndPass.getBytes())); httppost.addRequestHeader(AUTHORIZATION, "Basic " + encodedLogin); } else { // MJM - 20110520 String ticketParameter = request.getParameter("ticket"); if (ticketParameter != null) { ticketParameter = ticketParameter.trim(); if (!ticketParameter.isEmpty()) { Ticket ticket = TicketFactory.createInstance(); try { Map<String, String> props = ticket.getProperties(ticketParameter); user = props.get("user"); pass = props.get("pass"); String userAndPass = user + ":" + pass; String encodedLogin = new String(org.apache.commons.codec.binary.Base64 .encodeBase64(userAndPass.getBytes())); httppost.addRequestHeader(AUTHORIZATION, "Basic " + encodedLogin); } catch (Exception e) { log.info("-------------------------------------------"); log.info("EXCEPCTION THROWED BY PROXYREDIRECT CLASS"); log.info("METHOD: doPost"); log.info("TICKET VALUE: " + ticketParameter); log.info("-------------------------------------------"); } } } } } else { httppost.addRequestHeader(AUTHORIZATION, authorizationValue); } // FIN_PATH_TICKET_MJM-20112405-POST // FIN_PATH_MAPEAEDITA_SECURITY - AP String body = inputStreamAsString(request.getInputStream()); StringRequestEntity bodyEntity = new StringRequestEntity(body, null, null); if (0 == httppost.getParameters().length) { log.debug("No Name/Value pairs found ... pushing as received"); // PATCH httppost.setRequestEntity(bodyEntity); // PATCH } if (log.isDebugEnabled()) { log.debug("Body = " + body); NameValuePair[] nameValuePairs = httppost.getParameters(); log.debug("NameValuePairs found: " + nameValuePairs.length); for (int i = 0; i < nameValuePairs.length; ++i) { log.debug("parameters:" + nameValuePairs[i].toString()); } } if (!legend) client.getParams().setParameter("http.protocol.content-charset", "UTF-8"); if (soap) { httppost.addRequestHeader("SOAPAction", serverUrl); } client.executeMethod(httppost); // PATH_FOLLOW_REDIRECT_POST int j = 0; String redirectLocation; Header locationHeader = httppost.getResponseHeader("location"); while (locationHeader != null && j < numMaxRedirects) { redirectLocation = locationHeader.getValue(); // AGG 20111304 Aadimos el cuerpo de la peticin POST a // la nueva peticin redirigida // String bodyPost = httppost.getResponseBodyAsString(); StringRequestEntity bodyEntityPost = new StringRequestEntity(body, null, null); httppost.releaseConnection(); httppost = new PostMethod(redirectLocation); // AGG 20110912 Aadidas cabeceras peticin SOAP if (redirectLocation.toLowerCase().contains("wsdl")) { redirectLocation = serverUrl.replace("?wsdl", ""); httppost.addRequestHeader("SOAPAction", redirectLocation); httppost.addRequestHeader("Content-type", "text/xml"); } httppost.setRequestEntity(bodyEntityPost); client.executeMethod(httppost); locationHeader = httppost.getResponseHeader("location"); j++; } log.info("Number of followed redirections: " + j); if (locationHeader != null && j == numMaxRedirects) { log.error("The maximum number of redirects (" + numMaxRedirects + ") is exceed."); } // FIN_PATH_FOLLOW_REDIRECT_POST if (log.isDebugEnabled()) { Header[] responseHeaders = httppost.getResponseHeaders(); for (int i = 0; i < responseHeaders.length; ++i) { String headerName = responseHeaders[i].getName(); String headerValue = responseHeaders[i].getValue(); log.debug("responseHeaders:" + headerName + "=" + headerValue); } } // dump response to out if (httppost.getStatusCode() == HttpStatus.SC_OK) { // PATH_SECURITY_PROXY - AG Header[] respHeaders = httppost.getResponseHeaders(); int compSize = httppost.getResponseBody().length; ArrayList<Header> headerList = new ArrayList<Header>(Arrays.asList(respHeaders)); String headersString = headerList.toString(); checkedContent = checkContent(headersString, compSize, serverUrl); // FIN_PATH_SECURITY_PROXY - AG if (checkedContent == true) { /* * checks if it has requested an getfeatureinfo to modify the response content * type. */ String requesteredUrl = request.getParameter("url"); if (GETINFO_PLAIN_REGEX.matcher(requesteredUrl).matches()) { response.setContentType("text/plain"); } else if (GETINFO_GML_REGEX.matcher(requesteredUrl).matches()) { response.setContentType("application/gml+xml"); } else if (GETINFO_HTML_REGEX.matcher(requesteredUrl).matches()) { response.setContentType("text/html"); } else if (requesteredUrl.toLowerCase().contains("mapeaop=geosearch") || requesteredUrl.toLowerCase().contains("mapeaop=geoprint")) { response.setContentType("application/json"); } else { response.setContentType("text/xml"); } if (legend) { String responseBody = httppost.getResponseBodyAsString(); if (responseBody.contains("ServiceExceptionReport") && serverUrl.contains("LegendGraphic")) { response.sendRedirect("Componente/img/blank.gif"); } else { response.setContentLength(responseBody.length()); PrintWriter out = response.getWriter(); out.print(responseBody); response.flushBuffer(); } } else { // Patch_AGG 20112505 Prevents IE cache if (request.getProtocol().compareTo("HTTP/1.0") == 0) { response.setHeader("Pragma", "no-cache"); } else if (request.getProtocol().compareTo("HTTP/1.1") == 0) { response.setHeader("Cache-Control", "no-cache"); } response.setDateHeader("Expires", -1); // END patch // Copy request to response InputStream st = httppost.getResponseBodyAsStream(); final ServletOutputStream sos = response.getOutputStream(); IOUtils.copy(st, sos); } } else { strErrorMessage += errorType; log.error(strErrorMessage); } } else if (httppost.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); response.addHeader(WWW_AUTHENTICATE, httppost.getResponseHeader(WWW_AUTHENTICATE).getValue()); } else { strErrorMessage = "Unexpected failure: ".concat(httppost.getStatusLine().toString()) .concat(" ").concat(httppost.getResponseBodyAsString()); log.error("Unexpected failure: " + httppost.getStatusLine().toString()); } httppost.releaseConnection(); // AGG 20110927 Avoid Throwable (change it with exceptions) } catch (Exception e) { log.error("Error al tratar el contenido de la peticion: " + e.getMessage(), e); } finally { if (httppost != null) { httppost.releaseConnection(); } } } else { strErrorMessage += "Only HTTP(S) protocol supported"; log.error("Only HTTP(S) protocol supported"); // throw new // ServletException("only HTTP(S) protocol supported"); } } // There are errors. if (!strErrorMessage.equals("") || serverUrl.equals("ERROR")) { if (strErrorMessage.equals("") == true) { strErrorMessage = "Error en el parametro url de entrada"; } // String errorXML = strErrorMessage; String errorXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error><descripcion>" + strErrorMessage + "</descripcion></error>"; response.setContentType("text/xml"); try { PrintWriter out = response.getWriter(); out.print(errorXML); response.flushBuffer(); } catch (Exception e) { log.error(e); } } log.info("-------- End POST method --------"); }
From source file:hudson.plugins.simpleupdatesite.SimpleUpdateSitePlugIn.java
public String checkConnection(String url) throws HttpException, IOException, IllegalArgumentException { GetMethod method = new GetMethod(url); InputStream responseBodyAsStream = null; try {/* w w w. ja v a2 s . c om*/ method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); HttpClient client = new HttpClient(); client.getParams().setConnectionManagerTimeout(1000); client.getParams().setSoTimeout(1000); DefaultHttpMethodRetryHandler handler = new DefaultHttpMethodRetryHandler(1, false); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, handler); client.executeMethod(method); if (method.getStatusCode() >= 300) { throw new HttpException(); } responseBodyAsStream = method.getResponseBodyAsStream(); return IOUtils.toString(responseBodyAsStream, "UTF-8"); } finally { IOUtils.closeQuietly(responseBodyAsStream); method.releaseConnection(); } }
From source file:edu.uci.ics.pregelix.example.util.TestExecutor.java
private InputStream getHandleResult(String handle, OutputFormat fmt) throws Exception { final String url = "http://localhost:19002/query/result"; // Create a method instance. GetMethod method = new GetMethod(url); method.setQueryString(new NameValuePair[] { new NameValuePair("handle", handle) }); method.setRequestHeader("Accept", fmt.mimeType()); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); executeHttpMethod(method);//from w w w.ja v a2 s. co m return method.getResponseBodyAsStream(); }
From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java
private HttpStreamResponse executeStreamWithTimeout(final HttpMethodBase HttpMethod, int timeoutMillis) { client.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler(0, false)); ExecutorService service = Executors.newSingleThreadExecutor(); Future<HttpStreamResponse> future = service.submit(new Callable<HttpStreamResponse>() { @Override/*from w w w . ja v a2 s .co m*/ public HttpStreamResponse call() throws IOException { return executeStream(HttpMethod); } }); try { return future.get(timeoutMillis, TimeUnit.MILLISECONDS); } catch (Exception e) { String uriInfo = ""; try { uriInfo = " for " + HttpMethod.getURI(); } catch (Exception ie) { } LOG.warn("Http connection thread was interrupted or has timed out" + uriInfo, e); return null; } finally { service.shutdownNow(); } }