List of usage examples for org.apache.commons.httpclient.methods PostMethod getParameters
public NameValuePair[] getParameters()
From source file:com.liferay.mail.util.FuseMailHook.java
protected int executeMethod(PostMethod method) throws Exception { HttpClient client = getHttpClient(); int status = client.executeMethod(method); if (_log.isDebugEnabled()) { _log.debug("Posting to URI: " + method.getURI()); NameValuePair[] pairs = method.getParameters(); if (pairs.length > 0) { StringBundler sb = new StringBundler(pairs.length * 3 + 1); sb.append("With parameters:\n"); for (int i = 0; i < pairs.length; i++) { sb.append("\t"); sb.append(pairs[i]);/* ww w. ja v a 2 s . c om*/ sb.append("\n"); } _log.debug(sb.toString()); } _log.debug("Status: " + status); _log.debug("Response body: " + method.getResponseBodyAsString()); } return status; }
From source file:mapbuilder.ProxyRedirect.java
/*************************************************************************** * Process the HTTP Post request//w ww. j av a 2 s .co m */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { 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); } } String serverUrl = request.getHeader("serverUrl"); if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) { PostMethod httppost = new PostMethod(serverUrl); // Transfer bytes from in to out log.info("HTTP POST transfering..." + serverUrl); String body = inputStreamAsString(request.getInputStream()); HttpClient client = new HttpClient(); httppost.setRequestBody(body); if (0 == httppost.getParameters().length) { log.debug("No Name/Value pairs found ... pushing as raw_post_data"); httppost.setParameter("raw_post_data", body); } 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()); } } //httppost.setRequestContentLength(PostMethod.CONTENT_LENGTH_CHUNKED); client.executeMethod(httppost); if (log.isDebugEnabled()) { Header[] respHeaders = httppost.getResponseHeaders(); for (int i = 0; i < respHeaders.length; ++i) { String headerName = respHeaders[i].getName(); String headerValue = respHeaders[i].getValue(); log.debug("responseHeaders:" + headerName + "=" + headerValue); } } if (httppost.getStatusCode() == HttpStatus.SC_OK) { response.setContentType("text/xml"); String responseBody = httppost.getResponseBodyAsString(); // use encoding of the request or UTF8 String encoding = request.getCharacterEncoding(); if (encoding == null) encoding = "UTF-8"; response.setCharacterEncoding(encoding); log.info("responseEncoding:" + encoding); // do not set a content-length of the response (string length might not match the response byte size) //response.setContentLength(responseBody.length()); log.info("responseBody:" + responseBody); PrintWriter out = response.getWriter(); out.print(responseBody); } else { log.error("Unexpected failure: " + httppost.getStatusLine().toString()); } httppost.releaseConnection(); } else { throw new ServletException("only HTTP(S) protocol supported"); } } catch (Throwable e) { throw new ServletException(e); } }
From source file:com.benfante.jslideshare.SlideShareConnectorImpl.java
public InputStream sendMessage(String url, Map<String, String> parameters) throws IOException, SlideShareErrorException { HttpClient client = createHttpClient(); PostMethod method = new PostMethod(url); method.addParameter("api_key", this.apiKey); Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator(); while (entryIt.hasNext()) { Map.Entry<String, String> entry = entryIt.next(); method.addParameter(entry.getKey(), entry.getValue()); }// www. j a va2 s. c o m Date now = new Date(); String ts = Long.toString(now.getTime() / 1000); String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase(); method.addParameter("ts", ts); method.addParameter("hash", hash); logger.debug("Sending POST message to " + method.getURI().getURI() + " with parameters " + Arrays.toString(method.getParameters())); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.debug("Server replied with a " + statusCode + " HTTP status code (" + HttpStatus.getStatusText(statusCode) + ")"); throw new SlideShareErrorException(statusCode, HttpStatus.getStatusText(statusCode)); } if (logger.isDebugEnabled()) { logger.debug(method.getResponseBodyAsString()); } InputStream result = new ByteArrayInputStream(method.getResponseBody()); method.releaseConnection(); return result; }
From source file:es.juntadeandalucia.mapea.proxy.ProxyRedirect.java
/*************************************************************************** * Process the HTTP Post request/*from w w w . java2 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:org.alfresco.repo.publishing.slideshare.SlideShareConnectorImpl.java
public InputStream sendMessage(String url, Map<String, String> parameters) throws IOException, SlideShareErrorException { PostMethod method = new PostMethod(url); method.addParameter("api_key", this.apiKey); Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator(); while (entryIt.hasNext()) { Map.Entry<String, String> entry = entryIt.next(); method.addParameter(entry.getKey(), entry.getValue()); }//w w w . ja v a2s . co m Date now = new Date(); String ts = Long.toString(now.getTime() / 1000); String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase(); method.addParameter("ts", ts); method.addParameter("hash", hash); logger.debug("Sending POST message to " + method.getURI().getURI() + " with parameters " + Arrays.toString(method.getParameters())); int statusCode = httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.debug("Server replied with a " + statusCode + " HTTP status code (" + HttpStatus.getStatusText(statusCode) + ")"); throw new SlideShareErrorException(statusCode, HttpStatus.getStatusText(statusCode)); } if (logger.isDebugEnabled()) { logger.debug(method.getResponseBodyAsString()); } InputStream result = new ByteArrayInputStream(method.getResponseBody()); method.releaseConnection(); return result; }
From source file:org.biomart.martservice.MartServiceUtils.java
private static MartServiceException constructException(HttpMethod method, String martServiceLocation, Exception cause) {/* w w w . j av a 2s . c om*/ StringBuffer errorMessage = new StringBuffer(); errorMessage.append("Error posting to " + martServiceLocation + lineSeparator); if (cause == null) { errorMessage.append(" " + method.getStatusLine() + lineSeparator); } if (method instanceof PostMethod) { PostMethod postMethod = (PostMethod) method; NameValuePair[] data = postMethod.getParameters(); for (int i = 0; i < data.length; i++) { errorMessage.append(" " + data[i].getName() + " = " + data[i].getValue() + lineSeparator); } } else { errorMessage.append(method.getQueryString()); } return new MartServiceException(errorMessage.toString(), cause); }
From source file:org.eclipse.mylyn.tasks.tests.web.WebRepositoryConnectorTest.java
public void testEncodingParameters() throws Exception { TaskRepository repository = new TaskRepository(WebRepositoryConnector.REPOSITORY_TYPE, "http://foo.net"); repository.setAuthenticationCredentials("USER", "PASSWORD"); repository.setProperty(WebRepositoryConnector.PROPERTY_LOGIN_REQUEST_METHOD, WebRepositoryConnector.REQUEST_POST); repository.setProperty(WebRepositoryConnector.PROPERTY_LOGIN_REQUEST_URL, // "${serverUrl}/Login.php?xajax=xCheckUserLogin&xajaxargs[]=<xjxquery><q>${xjxquery}</q></xjxquery>"); repository.setProperty("param_xjxquery", "TestUserName=${userId}&TestUserPWD=${password}&HttpRefer="); Map<String, String> params = new HashMap<String, String>(); PostMethod method = (PostMethod) WebRepositoryConnector.getLoginMethod(params, repository); String form = EncodingUtil.formUrlEncode(method.getParameters(), method.getRequestCharSet()); assertEquals("xajax=xCheckUserLogin&" + // "xajaxargs%5B%5D=%3Cxjxquery%3E%3Cq%3E" + // "TestUserName%3DUSER%26" + // "TestUserPWD%3DPASSWORD%26" + // "HttpRefer%3D" + // "%3C%2Fq%3E%3C%2Fxjxquery%3E", form); }