List of usage examples for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER
String RETRY_HANDLER
To view the source code for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER.
Click Source Link
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 ww.ja v a2 s .c o 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// ww w .j av a2 s . c om ***************************************************************************/ 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: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 ww w . j a v a 2s .c o m*/ return method.getResponseBodyAsStream(); }
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 va2s .co m 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
public void executeDDL(String str, String url) throws Exception { // 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);// ww w . j av a 2s. co m }
From source file:fr.openwide.talendalfresco.rest.client.importer.RestImportFileTest.java
public void logout() { // create client and configure it HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout); // instantiating a new method and configuring it GetMethod method = new GetMethod(restCommandUrlPrefix + "logout"); method.setFollowRedirects(true); // ? // Provide custom retry handler is necessary (?) method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); NameValuePair[] params = new NameValuePair[] { new NameValuePair("ticket", ticket) }; // TODO always provide ticket method.setQueryString(params);/*from w ww . j a va2 s . c o m*/ try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } // Read the response body. byte[] responseBody = method.getResponseBody(); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data System.out.println(new String(responseBody)); } catch (HttpException e) { // TODO e.printStackTrace(); } catch (IOException e) { // TODO e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } }
From source file:net.sf.taverna.t2.activities.biomoby.ExecuteAsyncCgiService.java
private static boolean pollAsyncCgiService(String msName, String url, EndpointReference epr, String[] queryIds, String[] result) throws MobyException { // Needed to remap results HashMap<String, Integer> queryMap = new HashMap<String, Integer>(); for (int qi = 0; qi < queryIds.length; qi++) { String queryId = queryIds[qi]; if (queryId != null) queryMap.put(queryId, new Integer(qi)); }/* w w w .ja v a 2s . c o m*/ if (queryMap.size() == 0) return false; // construct the GetMultipleResourceProperties XML StringBuffer xml = new StringBuffer(); xml.append("<wsrf-rp:GetMultipleResourceProperties xmlns:wsrf-rp='" + RESOURCE_PROPERTIES_NS + "' xmlns:mobyws='http://biomoby.org/'>"); for (String q : queryMap.keySet()) xml.append("<wsrf-rp:ResourceProperty>mobyws:" + STATUS_PREFIX + q + "</wsrf-rp:ResourceProperty>"); xml.append("</wsrf-rp:GetMultipleResourceProperties>"); StringBuffer httpheader = new StringBuffer(); httpheader.append("<moby-wsrf>"); httpheader.append("<wsa:Action xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">" + GET_MULTIPLE_RESOURCE_PROPERTIES_ACTION + "</wsa:Action>"); httpheader.append( "<wsa:To xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsu:Id=\"To\">" + url + "</wsa:To>"); httpheader.append( "<mobyws:ServiceInvocationId xmlns:mobyws=\"http://biomoby.org/\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsa:IsReferenceParameter=\"true\">" + epr.getServiceInvocationId() + "</mobyws:ServiceInvocationId>"); httpheader.append("</moby-wsrf>"); AnalysisEvent[] l_ae = null; // First, status from queries String response = ""; // construct the Httpclient HttpClient client = new HttpClient(); client.getParams().setParameter("http.useragent", "jMoby/Taverna2"); // create the post method PostMethod method = new PostMethod(url + "/status"); // add the moby-wsrf header (with no newlines) method.addRequestHeader("moby-wsrf", httpheader.toString().replaceAll("\r\n", "")); // put our data in the request RequestEntity entity; try { entity = new StringRequestEntity(xml.toString(), "text/xml", null); } catch (UnsupportedEncodingException e) { throw new MobyException("Problem posting data to webservice", e); } method.setRequestEntity(entity); // retry up to 10 times client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(10, true)); // call the method try { if (client.executeMethod(method) != HttpStatus.SC_OK) throw new MobyException("Async HTTP POST service returned code: " + method.getStatusCode() + "\n" + method.getStatusLine() + "\nduring our polling request"); response = stream2String(method.getResponseBodyAsStream()); } catch (IOException e) { throw new MobyException("Problem reading response from webservice", e); } finally { // Release current connection to the connection pool once you // are // done method.releaseConnection(); } if (response != null) { l_ae = AnalysisEvent.createFromXML(response); } if (l_ae == null || l_ae.length == 0) { new MobyException("Troubles while checking asynchronous MOBY job status from service " + msName); } ArrayList<String> finishedQueries = new ArrayList<String>(); // Second, gather those finished queries for (int iae = 0; iae < l_ae.length; iae++) { AnalysisEvent ae = l_ae[iae]; if (ae.isCompleted()) { String queryId = ae.getQueryId(); if (!queryMap.containsKey(queryId)) { throw new MobyException( "Invalid result queryId on asynchronous MOBY job status fetched from " + msName); } finishedQueries.add(queryId); } } // Third, let's fetch the results from the finished queries if (finishedQueries.size() > 0) { String[] resQueryIds = finishedQueries.toArray(new String[0]); for (int x = 0; x < resQueryIds.length; x++) { // construct the GetMultipleResourceProperties XML xml = new StringBuffer(); xml.append("<wsrf-rp:GetMultipleResourceProperties xmlns:wsrf-rp='" + RESOURCE_PROPERTIES_NS + "' xmlns:mobyws='http://biomoby.org/'>"); for (String q : resQueryIds) xml.append("<wsrf-rp:ResourceProperty>mobyws:" + RESULT_PREFIX + q + "</wsrf-rp:ResourceProperty>"); xml.append("</wsrf-rp:GetMultipleResourceProperties>"); httpheader = new StringBuffer(); httpheader.append("<moby-wsrf>"); httpheader.append("<wsa:Action xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">" + GET_MULTIPLE_RESOURCE_PROPERTIES_ACTION + "</wsa:Action>"); httpheader.append( "<wsa:To xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsu:Id=\"To\">" + url + "</wsa:To>"); httpheader.append( "<mobyws:ServiceInvocationId xmlns:mobyws=\"http://biomoby.org/\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsa:IsReferenceParameter=\"true\">" + epr.getServiceInvocationId() + "</mobyws:ServiceInvocationId>"); httpheader.append("</moby-wsrf>"); client = new HttpClient(); client.getParams().setParameter("http.useragent", "jMoby/Taverna2"); // create the post method method = new PostMethod(url + "/results"); // add the moby-wsrf header (with no newlines) method.addRequestHeader("moby-wsrf", httpheader.toString().replaceAll("\r\n", "")); // put our data in the request entity = null; try { entity = new StringRequestEntity(xml.toString(), "text/xml", null); } catch (UnsupportedEncodingException e) { throw new MobyException("Problem posting data to webservice", e); } method.setRequestEntity(entity); // retry up to 10 times client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(10, true)); // call the method try { if (client.executeMethod(method) != HttpStatus.SC_OK) throw new MobyException("Async HTTP POST service returned code: " + method.getStatusCode() + "\n" + method.getStatusLine() + "\nduring our polling request"); // place the result in the array result[x] = stream2String(method.getResponseBodyAsStream()); // Marking as null queryIds[x] = null; } catch (IOException e) { logger.warn("Problem getting result from webservice\n" + e.getMessage()); } finally { // Release current connection method.releaseConnection(); } } } return finishedQueries.size() != queryMap.size(); }
From source file:hudson.plugins.simpleupdatesite.SimpleUpdateSitePlugIn.java
public String getUpdateSiteJSON(String url) throws HttpException, IOException { GetMethod method = new GetMethod(url); InputStream responseBodyAsStream = null; try {/*from ww w .ja va2 s.c o m*/ method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); HttpClient client = new HttpClient(); client.getParams().setConnectionManagerTimeout(Constant.HTTP_TIMEOUT); client.getParams().setSoTimeout(Constant.HTTP_TIMEOUT); DefaultHttpMethodRetryHandler handler = new DefaultHttpMethodRetryHandler(2, false); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, handler); client.executeMethod(method); responseBodyAsStream = method.getResponseBodyAsStream(); return IOUtils.toString(responseBodyAsStream, "UTF-8"); } finally { IOUtils.closeQuietly(responseBodyAsStream); method.releaseConnection(); } }
From source file:com.zenkey.net.prowser.Tab.java
/************************************************************************** * Configures the HttpMethod object before use. * /*ww w .ja v a2 s .co m*/ * @param httpMethod * The HTTP method object. * @param request * The request object. * @param ioTimeout * The timeout value to use for I/O operations (like making * connections and socket reads). This value should be 1 second * longer than the actual timeout used for the request, in order to * allow the request to timeout cleanly without having an I/O * exception get in the way. * @param httpMethodRetryHandler * The retry handler object. * @throws ProtocolException * If the HTTP version in the request object is invalid. */ private static void prepareHttpMethod(HttpMethod httpMethod, Request request, HttpMethodRetryHandler httpMethodRetryHandler) throws ProtocolException { httpMethod.setFollowRedirects(false); httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, httpMethodRetryHandler); String httpVersion = null; if ((httpVersion = request.getHttpVersion()) != null) httpMethod.getParams().setVersion(HttpVersion.parse("HTTP/" + httpVersion)); String userAgent = null; if ((userAgent = request.getUserAgent()) != null) httpMethod.getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent); }