List of usage examples for org.apache.commons.httpclient HttpMethod setFollowRedirects
public abstract void setFollowRedirects(boolean paramBoolean);
From source file:org.mulgara.resolver.http.HttpContent.java
/** * Obtain the approrpriate connection method * //from w w w .j a va 2 s .co m * @param methodType can be HEAD or GET * @return HttpMethodBase method */ private HttpMethod getConnectionMethod(int methodType) { if (methodType != GET && methodType != HEAD) { throw new IllegalArgumentException("Invalid method base supplied for connection"); } HostConfiguration config = new HostConfiguration(); config.setHost(host, port, Protocol.getProtocol(schema)); if (connection != null) { connection.releaseConnection(); connection.close(); connection = null; } try { connection = connectionManager.getConnectionWithTimeout(config, 0L); } catch (ConnectionPoolTimeoutException te) { // NOOP: SimpleHttpConnectionManager does not use timeouts } String proxyHost = System.getProperty("mulgara.httpcontent.proxyHost"); if (proxyHost != null && proxyHost.length() > 0) { connection.setProxyHost(proxyHost); } String proxyPort = System.getProperty("mulgara.httpcontent.proxyPort"); if (proxyPort != null && proxyPort.length() > 0) { connection.setProxyPort(Integer.parseInt(proxyPort)); } // default timeout to 30 seconds connection.getParams() .setConnectionTimeout(Integer.parseInt(System.getProperty("mulgara.httpcontent.timeout", "30000"))); String proxyUserName = System.getProperty("mulgara.httpcontent.proxyUserName"); if (proxyUserName != null) { state.setCredentials( new AuthScope(System.getProperty("mulgara.httpcontent.proxyRealmHost"), AuthScope.ANY_PORT, System.getProperty("mulgara.httpcontent.proxyRealm"), AuthScope.ANY_SCHEME), new UsernamePasswordCredentials(proxyUserName, System.getProperty("mulgara.httpcontent.proxyPassword"))); } HttpMethod method = null; if (methodType == HEAD) { method = new HeadMethod(httpUri.toString()); } else { method = new GetMethod(httpUri.toString()); } // manually follow redirects due to the // strictness of http client implementation method.setFollowRedirects(false); return method; }
From source file:org.nunux.poc.portal.ProxyServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link HttpServletResponse} * * @param httpMethodProxyRequest An object representing the proxy request to * be made/*w w w . j ava 2 s. c o m*/ * @param httpServletResponse An object by which we can send the proxied * response back to the client * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws ServletException Can be thrown to indicate that another error has * occurred */ private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { if (httpServletRequest.isSecure()) { Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443)); } // Create a default HttpClient HttpClient httpClient = new HttpClient(); httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); InputStream response = httpMethodProxyRequest.getResponseBodyAsStream(); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* * 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* * 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); if (followRedirects) { if (stringLocation.contains("jsessionid")) { Cookie cookie = new Cookie("JSESSIONID", stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11)); cookie.setPath("/"); httpServletResponse.addCookie(cookie); //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL"); } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) { Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie"); String[] cookieDetails = header.getValue().split(";"); String[] nameValue = cookieDetails[0].split("="); if (nameValue[0].equalsIgnoreCase("jsessionid")) { httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(), nameValue[1]); debug("redirecting: store jsessionid: " + nameValue[1]); } else { Cookie cookie = new Cookie(nameValue[0], nameValue[1]); cookie.setPath("/"); //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath()); httpServletResponse.addCookie(cookie); } } httpServletResponse.sendRedirect( stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName)); return; } } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked") || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth // proxy servlet does not support chunked encoding } else if (header.getName().equals("Set-Cookie")) { String[] cookieDetails = header.getValue().split(";"); String[] nameValue = cookieDetails[0].split("="); if (nameValue[0].equalsIgnoreCase("jsessionid")) { httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(), nameValue[1]); debug("redirecting: store jsessionid: " + nameValue[1]); } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } List<Header> responseHeaders = Arrays.asList(headerArrayResponse); if (isBodyParameterGzipped(responseHeaders)) { debug("GZipped: true"); int length = 0; if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) { String gz = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); intProxyResponseCode = HttpServletResponse.SC_OK; httpServletResponse.setHeader(STRING_LOCATION_HEADER, gz); } else { final byte[] bytes = ungzip(httpMethodProxyRequest.getResponseBody()); length = bytes.length; response = new ByteArrayInputStream(bytes); } httpServletResponse.setContentLength(length); } // Send the content to the client debug("Received status code: " + intProxyResponseCode, "Response: " + response); //httpServletResponse.getWriter().write(response); copy(response, httpServletResponse.getOutputStream()); }
From source file:org.nuxeo.opensocial.shindig.gadgets.NXHttpFetcher.java
/** {@inheritDoc} */ public HttpResponse fetch(HttpRequest request) { HttpClient httpClient = new HttpClient(); HttpMethod httpMethod; String methodType = request.getMethod(); String requestUri = request.getUri().toString(); ProxyHelper.fillProxy(httpClient, requestUri); // true for non-HEAD requests boolean requestCompressedContent = true; if ("POST".equals(methodType) || "PUT".equals(methodType)) { EntityEnclosingMethod enclosingMethod = ("POST".equals(methodType)) ? new PostMethod(requestUri) : new PutMethod(requestUri); if (request.getPostBodyLength() > 0) { enclosingMethod.setRequestEntity(new InputStreamRequestEntity(request.getPostBody())); enclosingMethod.setRequestHeader("Content-Length", String.valueOf(request.getPostBodyLength())); }// w ww .j a v a 2s . co m httpMethod = enclosingMethod; } else if ("DELETE".equals(methodType)) { httpMethod = new DeleteMethod(requestUri); } else if ("HEAD".equals(methodType)) { httpMethod = new HeadMethod(requestUri); } else { httpMethod = new GetMethod(requestUri); } httpMethod.setFollowRedirects(false); httpMethod.getParams().setSoTimeout(connectionTimeoutMs); if (requestCompressedContent) httpMethod.setRequestHeader("Accept-Encoding", "gzip, deflate"); for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) { httpMethod.setRequestHeader(entry.getKey(), StringUtils.join(entry.getValue(), ',')); } try { int statusCode = httpClient.executeMethod(httpMethod); // Handle redirects manually if (request.getFollowRedirects() && ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY) || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || (statusCode == HttpStatus.SC_SEE_OTHER) || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT))) { Header header = httpMethod.getResponseHeader("location"); if (header != null) { String redirectUri = header.getValue(); if ((redirectUri == null) || (redirectUri.equals(""))) { redirectUri = "/"; } httpMethod.releaseConnection(); httpMethod = new GetMethod(redirectUri); statusCode = httpClient.executeMethod(httpMethod); } } return makeResponse(httpMethod, statusCode); } catch (IOException e) { if (e instanceof java.net.SocketTimeoutException || e instanceof java.net.SocketException) { return HttpResponse.timeout(); } return HttpResponse.error(); } finally { httpMethod.releaseConnection(); } }
From source file:org.olat.modules.tu.IframeTunnelController.java
/** * Constructor for a tunnel component wrapper controller * /* w w w.j av a2 s. co m*/ * @param ureq the userrequest * @param wControl the windowcontrol * @param config the module configuration */ public IframeTunnelController(final UserRequest ureq, final WindowControl wControl, final ModuleConfiguration config) { super(ureq, wControl); // use iframe translator for generic iframe title text setTranslator(Util.createPackageTranslator(IFrameDisplayController.class, ureq.getLocale())); this.config = config; // configuration.... final int configVersion = config.getConfigurationVersion(); // since config version 1 final String proto = (String) config.get(TUConfigForm.CONFIGKEY_PROTO); final String host = (String) config.get(TUConfigForm.CONFIGKEY_HOST); final Integer port = (Integer) config.get(TUConfigForm.CONFIGKEY_PORT); final String user = (String) config.get(TUConfigForm.CONFIGKEY_USER); final String startUri = (String) config.get(TUConfigForm.CONFIGKEY_URI); final String pass = (String) config.get(TUConfigForm.CONFIGKEY_PASS); String firstQueryString = null; if (configVersion == 2) { // query string is available since config version 2 firstQueryString = (String) config.get(TUConfigForm.CONFIGKEY_QUERY); } final boolean usetunnel = config.getBooleanSafe(TUConfigForm.CONFIG_TUNNEL); myContent = createVelocityContainer("iframe_index"); if (!usetunnel) { // display content directly final String rawurl = TUConfigForm.getFullURL(proto, host, port, startUri, firstQueryString).toString(); myContent.contextPut("url", rawurl); } else { // tunnel final Identity ident = ureq.getIdentity(); if (user != null && user.length() > 0) { httpClientInstance = HttpClientFactory.getHttpClientInstance(host, port.intValue(), proto, user, pass); } else { httpClientInstance = HttpClientFactory.getHttpClientInstance(host, port.intValue(), proto, null, null); } final Locale loc = ureq.getLocale(); final Mapper mapper = new Mapper() { @Override public MediaResource handle(final String relPath, final HttpServletRequest hreq) { MediaResource mr = null; final String method = hreq.getMethod(); String uri = relPath; HttpMethod meth = null; if (uri == null) { uri = (startUri == null) ? "" : startUri; } if (uri.length() > 0 && uri.charAt(0) != '/') { uri = "/" + uri; } // String contentType = hreq.getContentType(); // if (allowedToSendPersonalHeaders) { final String userName = ident.getName(); final User u = ident.getUser(); final String lastName = u.getProperty(UserConstants.LASTNAME, loc); final String firstName = u.getProperty(UserConstants.FIRSTNAME, loc); final String email = u.getProperty(UserConstants.EMAIL, loc); if (method.equals("GET")) { final GetMethod cmeth = new GetMethod(uri); final String queryString = hreq.getQueryString(); if (queryString != null) { cmeth.setQueryString(queryString); } meth = cmeth; // if response is a redirect, follow it if (meth == null) { return null; } meth.setFollowRedirects(true); } else if (method.equals("POST")) { // if (contentType == null || contentType.equals("application/x-www-form-urlencoded")) { // regular post, no file upload // } final Map params = hreq.getParameterMap(); final PostMethod pmeth = new PostMethod(uri); final Set postKeys = params.keySet(); for (final Iterator iter = postKeys.iterator(); iter.hasNext();) { final String key = (String) iter.next(); final String vals[] = (String[]) params.get(key); for (int i = 0; i < vals.length; i++) { pmeth.addParameter(key, vals[i]); } meth = pmeth; } if (meth == null) { return null; // Redirects are not supported when using POST method! // See RFC 2616, section 10.3.3, page 62 } } // Add olat specific headers to the request, can be used by external // applications to identify user and to get other params // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py meth.addRequestHeader("X-OLAT-USERNAME", userName); meth.addRequestHeader("X-OLAT-LASTNAME", lastName); meth.addRequestHeader("X-OLAT-FIRSTNAME", firstName); meth.addRequestHeader("X-OLAT-EMAIL", email); boolean ok = false; try { httpClientInstance.executeMethod(meth); ok = true; } catch (final Exception e) { // handle error later } if (!ok) { // error meth.releaseConnection(); return new NotFoundMediaResource(relPath); } // get or post successfully final Header responseHeader = meth.getResponseHeader("Content-Type"); if (responseHeader == null) { // error return new NotFoundMediaResource(relPath); } mr = new HttpRequestMediaResource(meth); return mr; } }; final String amapPath = registerMapper(mapper); String alluri = amapPath + startUri; if (firstQueryString != null) { alluri += "?" + firstQueryString; } myContent.contextPut("url", alluri); } final String frameId = "ifdc" + hashCode(); // for e.g. js use myContent.contextPut("frameId", frameId); putInitialPanel(myContent); }
From source file:org.olat.modules.tu.TunnelComponent.java
/** * @param tuReq/*from w ww . j a va 2 s .c om*/ * @param client * @return HttpMethod */ public HttpMethod fetch(final TURequest tuReq, final HttpClient client) { final String modulePath = tuReq.getUri(); HttpMethod meth = null; final String method = tuReq.getMethod(); if (method.equals("GET")) { final GetMethod cmeth = new GetMethod(modulePath); final String queryString = tuReq.getQueryString(); if (queryString != null) { cmeth.setQueryString(queryString); } meth = cmeth; if (meth == null) { return null; } // if response is a redirect, follow it meth.setFollowRedirects(true); } else if (method.equals("POST")) { final String type = tuReq.getContentType(); if (type == null || type.equals("application/x-www-form-urlencoded")) { // regular post, no file upload } final PostMethod pmeth = new PostMethod(modulePath); final Set postKeys = tuReq.getParameterMap().keySet(); for (final Iterator iter = postKeys.iterator(); iter.hasNext();) { final String key = (String) iter.next(); final String vals[] = (String[]) tuReq.getParameterMap().get(key); for (int i = 0; i < vals.length; i++) { pmeth.addParameter(key, vals[i]); } meth = pmeth; } if (meth == null) { return null; // Redirects are not supported when using POST method! // See RFC 2616, section 10.3.3, page 62 } } // Add olat specific headers to the request, can be used by external // applications to identify user and to get other params // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py meth.addRequestHeader("X-OLAT-USERNAME", tuReq.getUserName()); meth.addRequestHeader("X-OLAT-LASTNAME", tuReq.getLastName()); meth.addRequestHeader("X-OLAT-FIRSTNAME", tuReq.getFirstName()); meth.addRequestHeader("X-OLAT-EMAIL", tuReq.getEmail()); try { client.executeMethod(meth); return meth; } catch (final Exception e) { meth.releaseConnection(); } return null; }
From source file:org.olat.user.propertyhandlers.ICQPropertyHandler.java
/** * @see org.olat.user.propertyhandlers.Generic127CharTextPropertyHandler#isValid(org.olat.core.gui.components.form.flexible.FormItem, java.util.Map) *//*from w ww . ja va2s .c o m*/ @SuppressWarnings({ "unchecked", "unused" }) @Override public boolean isValid(final FormItem formItem, final Map formContext) { boolean result; final TextElement textElement = (TextElement) formItem; OLog log = Tracing.createLoggerFor(this.getClass()); if (StringHelper.containsNonWhitespace(textElement.getValue())) { // Use an HttpClient to fetch a profile information page from ICQ. final HttpClient httpClient = HttpClientFactory.getHttpClientInstance(); final HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setConnectionManagerTimeout(2500); httpClient.setParams(httpClientParams); final HttpMethod httpMethod = new GetMethod(ICQ_NAME_VALIDATION_URL); final NameValuePair uinParam = new NameValuePair(ICQ_NAME_URL_PARAMETER, textElement.getValue()); httpMethod.setQueryString(new NameValuePair[] { uinParam }); // Don't allow redirects since otherwise, we won't be able to get the HTTP 302 further down. httpMethod.setFollowRedirects(false); try { // Get the user profile page httpClient.executeMethod(httpMethod); final int httpStatusCode = httpMethod.getStatusCode(); // Looking at the HTTP status code tells us whether a user with the given ICQ name exists. if (httpStatusCode == HttpStatus.SC_OK) { // ICQ tells us that a user name is valid if it sends an HTTP 200... result = true; } else if (httpStatusCode == HttpStatus.SC_MOVED_TEMPORARILY) { // ...and if it's invalid, it sends an HTTP 302. textElement.setErrorKey("form.name.icq.error", null); result = false; } else { // For HTTP status codes other than 200 and 302 we will silently assume that the given ICQ name is valid, but inform the user about this. textElement.setExampleKey("form.example.icqname.notvalidated", null); log.warn("ICQ name validation: Expected HTTP status 200 or 301, but got " + httpStatusCode); result = true; } } catch (final Exception e) { // In case of any exception, assume that the given ICQ name is valid (The opposite would block easily upon network problems), and inform the user about // this. textElement.setExampleKey("form.example.icqname.notvalidated", null); log.warn("ICQ name validation: Exception: " + e.getMessage()); result = true; } } else { result = true; } log = null; return result; }
From source file:org.olat.user.propertyhandlers.MSNPropertyHandler.java
/** * @see org.olat.user.propertyhandlers.Generic127CharTextPropertyHandler#isValid(org.olat.core.gui.components.form.flexible.FormItem, java.util.Map) *///from w w w . j av a 2 s . c o m @SuppressWarnings({ "unchecked" }) @Override public boolean isValid(final FormItem formItem, final Map formContext) { boolean result; final TextElement textElement = (TextElement) formItem; OLog log = Tracing.createLoggerFor(this.getClass()); if (StringHelper.containsNonWhitespace(textElement.getValue())) { // Use an HttpClient to fetch a profile information page from MSN. final HttpClient httpClient = HttpClientFactory.getHttpClientInstance(); final HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setConnectionManagerTimeout(2500); httpClient.setParams(httpClientParams); final HttpMethod httpMethod = new GetMethod(MSN_NAME_VALIDATION_URL); final NameValuePair idParam = new NameValuePair(MSN_NAME_URL_PARAMETER, textElement.getValue()); httpMethod.setQueryString(new NameValuePair[] { idParam }); // Don't allow redirects since otherwise, we won't be able to get the correct status httpMethod.setFollowRedirects(false); try { // Get the user profile page httpClient.executeMethod(httpMethod); final int httpStatusCode = httpMethod.getStatusCode(); // Looking at the HTTP status code tells us whether a user with the given MSN name exists. if (httpStatusCode == HttpStatus.SC_MOVED_PERMANENTLY) { // If the user exists, we get a 301... result = true; } else if (httpStatusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) { // ...and if the user doesn't exist, MSN sends a 500. textElement.setErrorKey("form.name.msn.error", null); result = false; } else { // For HTTP status codes other than 301 and 500 we will assume that the given MSN name is valid, but inform the user about this. textElement.setExampleKey("form.example.msnname.notvalidated", null); log.warn("MSN name validation: Expected HTTP status 301 or 500, but got " + httpStatusCode); result = true; } } catch (final Exception e) { // In case of any exception, assume that the given MSN name is valid (The opposite would block easily upon network problems), and inform the user about // this. textElement.setExampleKey("form.example.msnname.notvalidated", null); log.warn("MSN name validation: Exception: " + e.getMessage()); result = true; } } else { result = true; } log = null; return result; }
From source file:org.olat.user.propertyhandlers.XingPropertyHandler.java
/** * @see org.olat.user.propertyhandlers.Generic127CharTextPropertyHandler#isValid(org.olat.core.gui.components.form.flexible.FormItem, java.util.Map) *//*from w w w . j av a 2s. c om*/ @SuppressWarnings({ "unused", "unchecked" }) @Override public boolean isValid(final FormItem formItem, final Map formContext) { boolean result; final TextElement textElement = (TextElement) formItem; OLog log = Tracing.createLoggerFor(this.getClass()); if (StringHelper.containsNonWhitespace(textElement.getValue())) { final HttpClient httpClient = HttpClientFactory.getHttpClientInstance(); final HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setConnectionManagerTimeout(2500); httpClient.setParams(httpClientParams); try { // Could throw IllegalArgumentException if argument is not a valid url // (e.g. contains whitespaces) final HttpMethod httpMethod = new GetMethod(XING_NAME_VALIDATION_URL + textElement.getValue()); // Don't allow redirects since otherwise, we won't be able to get the correct status httpMethod.setFollowRedirects(false); // Get the user profile page httpClient.executeMethod(httpMethod); final int httpStatusCode = httpMethod.getStatusCode(); // Looking at the HTTP status code tells us whether a user with the given Xing name exists. if (httpStatusCode == HttpStatus.SC_OK) { // If the user exists, we get a 200... result = true; } else if (httpStatusCode == HttpStatus.SC_MOVED_PERMANENTLY) { // ... and if he doesn't exist, we get a 301. textElement.setErrorKey("form.name.xing.error", null); result = false; } else { // In case of any exception, assume that the given MSN name is valid (The opposite would block easily upon network problems), and inform the user // about this. textElement.setExampleKey("form.example.xingname.notvalidated", null); log.warn("Xing name validation: Expected HTTP status 200 or 301, but got " + httpStatusCode); result = true; } } catch (final IllegalArgumentException e) { // The xing name is not url compatible (e.g. contains whitespaces) textElement.setErrorKey("form.xingname.notvalid", null); result = false; } catch (final Exception e) { // In case of any exception, assume that the given MSN name is valid (The opposite would block easily upon network problems), and inform the user about // this. textElement.setExampleKey("form.example.xingname.notvalidated", null); log.warn("Xing name validation: Exception: " + e.getMessage()); result = true; } } else { result = true; } log = null; return result; }
From source file:org.openqa.selenium.remote.HttpCommandExecutor.java
public Response execute(Command command) throws Exception { CommandInfo info = nameToUrl.get(command.getName()); HttpMethod httpMethod = info.getMethod(remotePath, command); httpMethod.addRequestHeader("Accept", "application/json, image/png"); String payload = new BeanToJsonConverter().convert(command.getParameters()); if (httpMethod instanceof PostMethod) { ((PostMethod) httpMethod)/* w w w. j a va2 s . c o m*/ .setRequestEntity(new StringRequestEntity(payload, "application/json", "UTF-8")); } client.executeMethod(httpMethod); // TODO: SimonStewart: 2008-04-25: This is really shabby if (isRedirect(httpMethod)) { Header newLocation = httpMethod.getResponseHeader("location"); httpMethod = new GetMethod(newLocation.getValue()); httpMethod.setFollowRedirects(true); httpMethod.addRequestHeader("Accept", "application/json, image/png"); client.executeMethod(httpMethod); } return createResponse(httpMethod); }
From source file:org.owtf.runtime.core.ZestBasicRunner.java
private ZestResponse send(HttpClient httpclient, ZestRequest req) throws IOException { HttpMethod method; URI uri = new URI(req.getUrl().toString(), false); switch (req.getMethod()) { case "GET": method = new GetMethod(uri.toString()); // Can only redirect on GETs method.setFollowRedirects(req.isFollowRedirects()); break;/*from w w w. j a va2 s. c o m*/ case "POST": method = new PostMethod(uri.toString()); break; case "OPTIONS": method = new OptionsMethod(uri.toString()); break; case "HEAD": method = new HeadMethod(uri.toString()); break; case "PUT": method = new PutMethod(uri.toString()); break; case "DELETE": method = new DeleteMethod(uri.toString()); break; case "TRACE": method = new TraceMethod(uri.toString()); break; default: throw new IllegalArgumentException("Method not supported: " + req.getMethod()); } setHeaders(method, req.getHeaders()); for (Cookie cookie : req.getCookies()) { // Replace any Zest variables in the value cookie.setValue(this.replaceVariablesInString(cookie.getValue(), false)); httpclient.getState().addCookie(cookie); } if (req.getMethod().equals("POST")) { // Do this after setting the headers so the length is corrected RequestEntity requestEntity = new StringRequestEntity(req.getData(), null, null); ((PostMethod) method).setRequestEntity(requestEntity); } int code = 0; String responseHeader = null; String responseBody = null; Date start = new Date(); try { this.debug(req.getMethod() + " : " + req.getUrl()); code = httpclient.executeMethod(method); responseHeader = method.getStatusLine().toString() + "\n" + arrayToStr(method.getResponseHeaders()); // httpclient.getParams().setParameter("http.method.response.buffer.warnlimit",new Integer(1000000000)); responseBody = method.getResponseBodyAsString(); } finally { method.releaseConnection(); } // Update the headers with the ones actually sent req.setHeaders(arrayToStr(method.getRequestHeaders())); return new ZestResponse(req.getUrl(), responseHeader, responseBody, code, new Date().getTime() - start.getTime()); }