List of usage examples for org.apache.commons.httpclient HttpStatus SC_MOVED_TEMPORARILY
int SC_MOVED_TEMPORARILY
To view the source code for org.apache.commons.httpclient HttpStatus SC_MOVED_TEMPORARILY.
Click Source Link
From source file:fr.dutra.confluence2wordpress.util.UrlUtils.java
private static URI followRedirectsInternal(URI url, int maxRedirections) { URI response = url;/* w ww . jav a 2s. c o m*/ HttpClient client = new HttpClient(); DefaultHttpMethodRetryHandler handler = new DefaultHttpMethodRetryHandler(1, false); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, handler); HttpMethod method = new HeadMethod(url.toASCIIString()); //method.setRequestHeader("Accept-Language", locale.getLanguage() + ",en"); method.setFollowRedirects(false); try { int statusCode = client.executeMethod(method); if ((statusCode == HttpStatus.SC_MOVED_PERMANENTLY) | (statusCode == HttpStatus.SC_MOVED_TEMPORARILY)) { if (maxRedirections > 0) { Header location = method.getResponseHeader("Location"); if (!location.getValue().equals("")) { // recursively check URL until it's not redirected any more // locations can be relative to previous URL URI target = url.resolve(location.getValue()); response = followRedirectsInternal(target, maxRedirections - 1); } } } } catch (Exception e) { //HttpClient can also throw IllegalArgumentException when URLs are malformed } return response; }
From source file:net.sourceforge.jwbf.actions.HttpActionClient.java
/** * Process a POST Message.//w w w .jav a2 s . co m * * @param authpost * a * @param cp * a * @return a returning message, not null * @throws IOException on problems * @throws ProcessException on problems * @throws CookieException on problems */ protected String post(HttpMethod authpost, ContentProcessable cp) throws IOException, ProcessException, CookieException { showCookies(client); authpost.getParams().setParameter("http.protocol.content-charset", MediaWikiBot.CHARSET); String out = ""; client.executeMethod(authpost); // Header locationHeader = authpost.getResponseHeader("location"); // if (locationHeader != null) { // authpost.setRequestHeader(locationHeader) ; // } // Usually a successful form-based login results in a redicrect to // another url int statuscode = authpost.getStatusCode(); if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header header = authpost.getResponseHeader("location"); if (header != null) { String newuri = header.getValue(); if ((newuri == null) || (newuri.equals(""))) { newuri = "/"; } LOG.debug("Redirect target: " + newuri); GetMethod redirect = new GetMethod(newuri); client.executeMethod(redirect); LOG.debug("Redirect: " + redirect.getStatusLine().toString()); // release any connection resources used by the method authpost.releaseConnection(); authpost = redirect; } } out = authpost.getResponseBodyAsString(); out = cp.processReturningText(out, authpost); cp.validateReturningCookies(client.getState().getCookies(), authpost); authpost.releaseConnection(); LOG.debug(authpost.getURI() + " || " + "POST: " + authpost.getStatusLine().toString()); return out; }
From source file:com.cloud.utils.net.HTTPUtils.java
/** * @param responseCode/* ww w. jav a 2 s .c o m*/ * @return */ public static boolean verifyResponseCode(int responseCode) { switch (responseCode) { case HttpStatus.SC_OK: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: return true; default: return false; } }
From source file:com.djimenez.tuenti.example.FormLoginDemo.java
/** * @param client/*from w w w .j av a2s . c om*/ * @param authpost * @throws IOException * @throws HttpException */ private static void manageRequest(final HttpClient client, final PostMethod authpost) throws IOException { // Usually a successful form-based login results in a redicrect to // another url final int statuscode = authpost.getStatusCode(); if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { final Header header = authpost.getResponseHeader("location"); checkHeader(client, header); } }
From source file:fr.unix_experience.owncloud_sms.engine.OCHttpClient.java
private int followRedirections(HttpMethod httpMethod) throws IOException { int redirectionsCount = 0; int status = httpMethod.getStatusCode(); while (redirectionsCount < 3 && (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header location = httpMethod.getResponseHeader("Location"); if (location == null) { location = httpMethod.getResponseHeader("location"); }//from w w w.ja va 2 s. co m if (location == null) { Log.e(TAG, "No valid location header found when redirecting."); return 500; } try { httpMethod.setURI(new URI(location.getValue())); } catch (URIException e) { Log.e(TAG, "Invalid URI in 302 FOUND response"); return 500; } status = executeMethod(httpMethod); redirectionsCount++; } if (redirectionsCount >= 3 && status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT) { Log.e(TAG, "Too many redirection done. Aborting, please ensure your server is " + "correctly configured"); return 400; } return status; }
From source file:com.ms.commons.utilities.HttpClientUtils.java
/** * <pre>/*from w w w. j a v a 2 s. c o m*/ * * * try { * inputStream = getResponseBodyAsStream(method, tryTimes, soTimeoutMill); * } finally { * IOUtils.closeQuietly(inputStream); * method.releaseConnection(); * } * * @param method * @param tryTimes * @param soTimeoutMill * @return */ public static InputStream getResponseBodyAsStream(HttpMethod method, Integer tryTimes, Integer soTimeoutMill) { init(); if (tryTimes == null) { tryTimes = 1; } if (soTimeoutMill == null) { soTimeoutMill = 20000; } method.getParams().setSoTimeout(soTimeoutMill); for (int i = 0; i < tryTimes; i++) { try { int responseCode = client.executeMethod(method); if (responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_MOVED_PERMANENTLY || responseCode == HttpStatus.SC_MOVED_TEMPORARILY) { return method.getResponseBodyAsStream(); } logger.error(String.format( "getResponseBodyAsString failed, responseCode: %s, should be 200, 301, 302", responseCode)); } catch (Exception e) { logger.error("getResponseBodyAsString failed", e); } finally { // method releaseConnection ResponseStream ResponseStream // ?finally { method.releaseConnection } // method.releaseConnection(); } } return null; }
From source file:com.mirth.connect.client.core.UpdateClient.java
public void sendUsageStatistics() throws ClientException { // Only send stats if they haven't been sent in the last 24 hours. long now = System.currentTimeMillis(); Long lastUpdate = client.getUpdateSettings().getLastStatsTime(); if (lastUpdate != null) { long last = lastUpdate; // 86400 seconds in a day if ((now - last) < (86400 * 1000)) { return; }//from w w w .j av a2s . co m } List<UsageData> usageData = null; try { usageData = getUsageData(); } catch (Exception e) { throw new ClientException(e); } HttpClientParams httpClientParams = new HttpClientParams(); HttpConnectionManager httpConnectionManager = new SimpleHttpConnectionManager(); httpClientParams.setSoTimeout(10 * 1000); httpConnectionManager.getParams().setConnectionTimeout(10 * 1000); httpConnectionManager.getParams().setSoTimeout(10 * 1000); HttpClient httpClient = new HttpClient(httpClientParams, httpConnectionManager); PostMethod post = new PostMethod(client.getUpdateSettings().getUpdateUrl() + URL_USAGE_STATISTICS); NameValuePair[] params = { new NameValuePair("serverId", client.getServerId()), new NameValuePair("version", client.getVersion()), new NameValuePair("data", serializer.toXML(usageData)) }; post.setRequestBody(params); try { int statusCode = httpClient.executeMethod(post); if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_MOVED_TEMPORARILY)) { throw new Exception("Failed to connect to update server: " + post.getStatusLine()); } // Save the sent time if sending was successful. UpdateSettings settings = new UpdateSettings(); settings.setLastStatsTime(now); client.setUpdateSettings(settings); } catch (Exception e) { throw new ClientException(e); } finally { post.releaseConnection(); } }
From source file:com.bluexml.side.framework.alfresco.webscriptExtension.SiteScriptExtension.java
/** * Method to create a site//from w w w. j a va 2 s . c om * The site is created through an http post call using a json structure as done by Share. * The json structure is of the form: * { * "visibility" : "PUBLIC", * "title" : "My Test Site100", * "shortName" : "mytestsite100", * "description" : "My Test Site created from command line 100", * "sitePreset" : "site-dashboard" * }, * * @param baseUrl the base url * @param alfrescoUsername the alfresco user login to use to send request * @param alfrescoUsername the alfresco password to use to send request * @param siteTitle the site title * @param siteShortname the mandatory site short name * @param siteDescription the site description * @param siteVisibility the site visibility * @param sitePreset the site preset * * @return nodeRef of the site; null if the site failed to be created; in the javascript, use site.getSite(siteShortname) to get the site. */ public NodeRef createSite(String baseUrl, String alfrescoUsername, String alfrescoPwd, String siteTitle, String siteShortname, String siteDescription, String siteVisibility, String sitePreset) { if (logger.isDebugEnabled()) { logger.debug("Create site " + siteTitle + " - sitheShortname =" + siteShortname + " - siteDescription=" + siteDescription); logger.debug(" - siteVisibility =" + siteVisibility + " - sitePreset=" + sitePreset); logger.debug(" - baseUrl =" + baseUrl + " - alfrescoUsername=" + alfrescoUsername + " - alfrescoPwd=" + alfrescoPwd); } NodeRef nodeRef = null; if (siteShortname != null) { SiteInfo siteInfo = siteService.getSite(siteShortname); if (siteInfo == null) { if (siteTitle == null) siteTitle = siteShortname; if (siteDescription == null) siteDescription = ""; if (sitePreset == null) sitePreset = "site-dashboard"; if (siteVisibility == null || !siteVisibility.equals(ScriptSiteService.PUBLIC_SITE) || !siteVisibility.equals(ScriptSiteService.MODERATED_SITE) || !siteVisibility.equals(ScriptSiteService.PRIVATE_SITE)) siteVisibility = ScriptSiteService.PUBLIC_SITE; if (baseUrl == null) baseUrl = BASE_URL; // Create Apache HTTP Client to use for both calls: login and create-site HttpClient httpClient = new HttpClient(); // Login to Share to get a JSESSIONID setup in HTTP Client String loginData = "username=" + alfrescoUsername + "&password=" + alfrescoPwd; makePostCall(httpClient, baseUrl + LOGIN_URL, loginData, CONTENT_TYPE_FORM, "Login to Alfresco Share", HttpStatus.SC_MOVED_TEMPORARILY, alfrescoUsername); // create body request using site parameters JSONObject json = new JSONObject(); try { json.put("visibility", siteVisibility); json.put("title", siteTitle); json.put("shortName", siteShortname); json.put("description", siteDescription); json.put("sitePreset", sitePreset); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } // send create-site request makePostCall(httpClient, baseUrl + CREATE_SITE_URL, json.toString(), CONTENT_TYPE_JSON, "Create site with name: " + siteShortname, HttpStatus.SC_OK, alfrescoUsername); siteInfo = siteService.getSite(siteShortname); if (siteInfo != null) { nodeRef = siteInfo.getNodeRef(); } else { // Site already exists, cannot create it, continue with next one logger.warn("Site (" + siteShortname + ") has not been created !!! - Check log."); } } else { // Site already exists, cannot create it, continue with next one logger.warn("Site (" + siteShortname + ") already exists, cannot create it"); } } else { // Site shortname is mandatory logger.warn("Site shortName parameter is mandatory, cannot create site without shortName"); } return nodeRef; }
From source file:com.autentia.mvn.plugin.changes.HttpRequest.java
/** * Send a GET method request to the given link using the configured HttpClient, possibly following redirects, and returns * the response as String./*from ww w .ja va 2 s .c o m*/ * * @param cl the HttpClient * @param link the URL * @throws HttpStatusException * @throws IOException */ public byte[] sendPostRequest(final HttpClient cl, final String link, final String parameters) throws HttpStatusException, IOException { try { final PostMethod pm = new PostMethod(link); if (parameters != null) { final String[] params = parameters.split("&"); for (final String param : params) { final String[] pair = param.split("="); if (pair.length == 2) { pm.addParameter(pair[0], pair[1]); } } } this.getLog().info("Downloading from Bugzilla at: " + link); cl.executeMethod(pm); final StatusLine sl = pm.getStatusLine(); if (sl == null) { this.getLog().error("Unknown error validating link: " + link); throw new HttpStatusException("UNKNOWN STATUS"); } // if we get a redirect, throws exception if (pm.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { this.getLog().debug("Attempt to redirect "); throw new HttpStatusException("Attempt to redirect"); } if (pm.getStatusCode() == HttpStatus.SC_OK) { final InputStream is = pm.getResponseBodyAsStream(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final byte[] buff = new byte[256]; int readed = is.read(buff); while (readed != -1) { baos.write(buff, 0, readed); readed = is.read(buff); } this.getLog().debug("Downloading from Bugzilla was successful"); return baos.toByteArray(); } else { this.getLog().warn("Downloading from Bugzilla failed. Received: [" + pm.getStatusCode() + "]"); throw new HttpStatusException("WRONG STATUS"); } } catch (final HttpException e) { if (this.getLog().isDebugEnabled()) { this.getLog().error("Error downloading issues from Bugzilla:", e); } else { this.getLog().error("Error downloading issues from Bugzilla url: " + e.getLocalizedMessage()); } throw e; } catch (final IOException e) { if (this.getLog().isDebugEnabled()) { this.getLog().error("Error downloading issues from Bugzilla:", e); } else { this.getLog().error("Error downloading issues from Bugzilla. Cause is " + e.getLocalizedMessage()); } throw e; } }
From source file:edu.ucsd.xmlrpc.xmlrpc.client.XmlRpcCommonsTransport.java
protected boolean isRedirectRequired() { switch (method.getStatusCode()) { case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_SEE_OTHER: case HttpStatus.SC_TEMPORARY_REDIRECT: return true; default://from ww w.j ava2s . c o m return false; } }