Java Code Examples for org.apache.commons.httpclient.HttpMethod#setFollowRedirects()
The following examples show how to use
org.apache.commons.httpclient.HttpMethod#setFollowRedirects() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProxyFilter.java From development with Apache License 2.0 | 5 votes |
/** * Will create the method and execute it. After this the method is sent to a * ResponseHandler that is returned. * * @param httpRequest * Request we are receiving from the client * @param url * The location we are proxying to * @return A ResponseHandler that can be used to write the response * @throws MethodNotAllowedException * If the method specified by the request isn't handled * @throws IOException * When there is a problem with the streams * @throws HttpException * The httpclient can throw HttpExcetion when executing the * method */ ResponseHandler executeRequest(HttpServletRequest httpRequest, String url) throws MethodNotAllowedException, IOException, HttpException { RequestHandler requestHandler = RequestHandlerFactory .createRequestMethod(httpRequest.getMethod()); HttpMethod method = requestHandler.process(httpRequest, url); method.setFollowRedirects(false); /* * Why does method.validate() return true when the method has been * aborted? I mean, if validate returns true the API says that means * that the method is ready to be executed. TODO I don't like doing type * casting here, see above. */ if (!((HttpMethodBase) method).isAborted()) { httpClient.executeMethod(method); if (method.getStatusCode() == 405) { Header allow = method.getResponseHeader("allow"); String value = allow.getValue(); throw new MethodNotAllowedException( "Status code 405 from server", AllowedMethodHandler.processAllowHeader(value)); } } return ResponseHandlerFactory.createResponseHandler(method); }
Example 2
Source File: CloudMetadataScanner.java From zap-extensions with Apache License 2.0 | 5 votes |
void sendMessageWithCustomHostHeader(HttpMessage message, String host) throws IOException { HttpMethodParams params = new HttpMethodParams(); params.setVirtualHost(host); HttpMethod method = createRequestMethod(message.getRequestHeader(), message.getRequestBody(), params); if (!(method instanceof EntityEnclosingMethod) || method instanceof ZapGetMethod) { method.setFollowRedirects(false); } User forceUser = getParent().getHttpSender().getUser(message); message.setTimeSentMillis(System.currentTimeMillis()); if (forceUser != null) { getParent() .getHttpSender() .executeMethod(method, forceUser.getCorrespondingHttpState()); } else { getParent().getHttpSender().executeMethod(method, null); } message.setTimeElapsedMillis( (int) (System.currentTimeMillis() - message.getTimeSentMillis())); HttpMethodHelper.updateHttpRequestHeaderSent(message.getRequestHeader(), method); HttpResponseHeader resHeader = HttpMethodHelper.getHttpResponseHeader(method); resHeader.setHeader(HttpHeader.TRANSFER_ENCODING, null); message.setResponseHeader(resHeader); message.getResponseBody().setCharset(resHeader.getCharset()); message.getResponseBody().setLength(0); message.getResponseBody().append(method.getResponseBody()); message.setResponseFromTargetHost(true); getParent().notifyNewMessage(this, message); }
Example 3
Source File: CloudMetadataScanner.java From zap-extensions with Apache License 2.0 | 5 votes |
private static HttpMethod createRequestMethod( HttpRequestHeader header, HttpBody body, HttpMethodParams params) throws URIException { HttpMethod httpMethod = new ZapGetMethod(); httpMethod.setURI(header.getURI()); httpMethod.setParams(params); params.setVersion(HttpVersion.HTTP_1_1); String msg = header.getHeadersAsString(); String[] split = Pattern.compile("\\r\\n", Pattern.MULTILINE).split(msg); String token = null; String name = null; String value = null; int pos = 0; for (int i = 0; i < split.length; i++) { token = split[i]; if (token.equals("")) { continue; } if ((pos = token.indexOf(":")) < 0) { return null; } name = token.substring(0, pos).trim(); value = token.substring(pos + 1).trim(); httpMethod.addRequestHeader(name, value); } if (body != null && body.length() > 0 && (httpMethod instanceof EntityEnclosingMethod)) { EntityEnclosingMethod post = (EntityEnclosingMethod) httpMethod; post.setRequestEntity(new ByteArrayRequestEntity(body.getBytes())); } httpMethod.setFollowRedirects(false); return httpMethod; }
Example 4
Source File: WebdavFileObject.java From commons-vfs with Apache License 2.0 | 5 votes |
/** * Prepares a Method object. * * @param method the HttpMethod. * @throws FileSystemException if an error occurs encoding the uri. * @throws URIException if the URI is in error. */ @Override protected void setupMethod(final HttpMethod method) throws FileSystemException, URIException { final String pathEncoded = ((URLFileName) getName()).getPathQueryEncoded(this.getUrlCharset()); method.setPath(pathEncoded); method.setFollowRedirects(this.getFollowRedirect()); method.setRequestHeader("User-Agent", "Jakarta-Commons-VFS"); method.addRequestHeader("Cache-control", "no-cache"); method.addRequestHeader("Cache-store", "no-store"); method.addRequestHeader("Pragma", "no-cache"); method.addRequestHeader("Expires", "0"); }
Example 5
Source File: AbstractHttpClient.java From alfresco-core with GNU Lesser General Public License v3.0 | 4 votes |
protected HttpMethod createMethod(Request req) throws IOException { StringBuilder url = new StringBuilder(128); url.append(baseUrl); url.append("/service/"); url.append(req.getFullUri()); // construct method HttpMethod httpMethod = null; String method = req.getMethod(); if(method.equalsIgnoreCase("GET")) { GetMethod get = new GetMethod(url.toString()); httpMethod = get; httpMethod.setFollowRedirects(true); } else if(method.equalsIgnoreCase("POST")) { PostMethod post = new PostMethod(url.toString()); httpMethod = post; ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(req.getBody(), req.getType()); if (req.getBody().length > DEFAULT_SAVEPOST_BUFFER) { post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); } post.setRequestEntity(requestEntity); // Note: not able to automatically follow redirects for POST, this is handled by sendRemoteRequest } else if(method.equalsIgnoreCase("HEAD")) { HeadMethod head = new HeadMethod(url.toString()); httpMethod = head; httpMethod.setFollowRedirects(true); } else { throw new AlfrescoRuntimeException("Http Method " + method + " not supported"); } if (req.getHeaders() != null) { for (Map.Entry<String, String> header : req.getHeaders().entrySet()) { httpMethod.setRequestHeader(header.getKey(), header.getValue()); } } return httpMethod; }
Example 6
Source File: TunnelComponent.java From olat with Apache License 2.0 | 4 votes |
/** * @param tuReq * @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; }
Example 7
Source File: ICQPropertyHandler.java From olat with Apache License 2.0 | 4 votes |
/** */ @SuppressWarnings({ "unchecked", "unused" }) @Override public boolean isValid(final FormItem formItem, final Map formContext) { boolean result; final TextElement textElement = (TextElement) formItem; 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; } return result; }
Example 8
Source File: MSNPropertyHandler.java From olat with Apache License 2.0 | 4 votes |
/** */ @SuppressWarnings({ "unchecked" }) @Override public boolean isValid(final FormItem formItem, final Map formContext) { boolean result; final TextElement textElement = (TextElement) formItem; 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; } return result; }
Example 9
Source File: TunnelComponent.java From olat with Apache License 2.0 | 4 votes |
/** * @param tuReq * @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; }
Example 10
Source File: ICQPropertyHandler.java From olat with Apache License 2.0 | 4 votes |
/** */ @SuppressWarnings({ "unchecked", "unused" }) @Override public boolean isValid(final FormItem formItem, final Map formContext) { boolean result; final TextElement textElement = (TextElement) formItem; 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; } return result; }
Example 11
Source File: MSNPropertyHandler.java From olat with Apache License 2.0 | 4 votes |
/** */ @SuppressWarnings({ "unchecked" }) @Override public boolean isValid(final FormItem formItem, final Map formContext) { boolean result; final TextElement textElement = (TextElement) formItem; 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; } return result; }
Example 12
Source File: Proxy.java From odo with Apache License 2.0 | 4 votes |
/** * Execute a request * * @param httpMethodProxyRequest * @param httpServletRequest * @param httpServletResponse * @param history * @throws Exception */ private void executeRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, PluginResponse httpServletResponse, History history) throws Exception { int intProxyResponseCode = 999; // Create a default HttpClient HttpClient httpClient = new HttpClient(); HttpState state = new HttpState(); try { httpMethodProxyRequest.setFollowRedirects(false); ArrayList<String> headersToRemove = getRemoveHeaders(); httpClient.getParams().setSoTimeout(60000); httpServletRequest.setAttribute("com.groupon.odo.removeHeaders", headersToRemove); // exception handling for httpclient HttpMethodRetryHandler noretryhandler = new HttpMethodRetryHandler() { public boolean retryMethod( final HttpMethod method, final IOException exception, int executionCount) { return false; } }; httpMethodProxyRequest.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, noretryhandler); intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest.getHostConfiguration(), httpMethodProxyRequest, state); } catch (Exception e) { // Return a gateway timeout httpServletResponse.setStatus(504); httpServletResponse.setHeader(Constants.HEADER_STATUS, "504"); httpServletResponse.flushBuffer(); return; } logger.info("Response code: {}, {}", intProxyResponseCode, HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString())); // 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) { // remove transfer-encoding header. The http libraries will handle this encoding if (header.getName().toLowerCase().equals("transfer-encoding")) { continue; } httpServletResponse.setHeader(header.getName(), header.getValue()); } // there is no data for a HTTP 304 or 204 if (intProxyResponseCode != HttpServletResponse.SC_NOT_MODIFIED && intProxyResponseCode != HttpServletResponse.SC_NO_CONTENT) { // Send the content to the client httpServletResponse.resetBuffer(); httpServletResponse.getOutputStream().write(httpMethodProxyRequest.getResponseBody()); } // copy cookies to servlet response for (Cookie cookie : state.getCookies()) { javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue()); if (cookie.getPath() != null) { servletCookie.setPath(cookie.getPath()); } if (cookie.getDomain() != null) { servletCookie.setDomain(cookie.getDomain()); } // convert expiry date to max age if (cookie.getExpiryDate() != null) { servletCookie.setMaxAge((int) ((cookie.getExpiryDate().getTime() - System.currentTimeMillis()) / 1000)); } servletCookie.setSecure(cookie.getSecure()); servletCookie.setVersion(cookie.getVersion()); if (cookie.getComment() != null) { servletCookie.setComment(cookie.getComment()); } httpServletResponse.addCookie(servletCookie); } }
Example 13
Source File: HttpFileObject.java From commons-vfs with Apache License 2.0 | 3 votes |
/** * Prepares a HttpMethod object. * * @param method The object which gets prepared to access the file object. * @throws FileSystemException if an error occurs. * @throws URIException if path cannot be represented. * @since 2.0 (was package) */ protected void setupMethod(final HttpMethod method) throws FileSystemException, URIException { final String pathEncoded = ((URLFileName) getName()).getPathQueryEncoded(this.getUrlCharset()); method.setPath(pathEncoded); method.setFollowRedirects(this.getFollowRedirect()); method.setRequestHeader("User-Agent", this.getUserAgent()); }