List of usage examples for org.apache.commons.httpclient HttpStatus SC_MOVED_PERMANENTLY
int SC_MOVED_PERMANENTLY
To view the source code for org.apache.commons.httpclient HttpStatus SC_MOVED_PERMANENTLY.
Click Source Link
From source file:com.djimenez.tuenti.example.FormLoginDemo.java
/** * @param client//from w w w . ja v a2 s.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:com.ms.commons.utilities.HttpClientUtils.java
/** * <pre>//from w ww . ja v a2 s . co 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: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 ava 2 s . c om*/ return false; } }
From source file:com.baidu.qa.service.test.client.HttpReqImpl.java
/** * use httpclient//from w w w . j a va 2s . c om * @param file * @param config * @param vargen * @return */ public Object requestHttpByHttpClient(File file, Config config, VariableGenerator vargen) { FileCharsetDetector det = new FileCharsetDetector(); try { String oldcharset = det.guestFileEncoding(file); if (oldcharset.equalsIgnoreCase("UTF-8") == false) FileUtil.transferFile(file, oldcharset, "UTF-8"); } catch (Exception ex) { log.error("[change expect file charset error]:" + ex); } Map<String, String> datalist = FileUtil.getMapFromFile(file, "="); if (datalist.size() <= 1) { return true; } if (!datalist.containsKey(Constant.KW_ITEST_HOST) && !datalist.containsKey(Constant.KW_ITEST_URL)) { log.error("[wrong file]:" + file.getName() + " hasn't Url"); return null; } if (datalist.containsKey(Constant.KW_ITEST_HOST)) { this.url = datalist.get(Constant.KW_ITEST_HOST); this.hashost = true; datalist.remove(Constant.KW_ITEST_HOST); } else { String action = datalist.get(Constant.KW_ITEST_URL); if (config.getHost().lastIndexOf("/") == config.getHost().length() - 1 && action.indexOf("/") == 0) { action = action.substring(1); } this.url = config.getHost() + action; datalist.remove("itest_url"); } if (datalist.containsKey(Constant.KW_ITEST_EXPECT)) { this.itest_expect = datalist.get(Constant.KW_ITEST_EXPECT); datalist.remove(Constant.KW_ITEST_EXPECT); } if (datalist.containsKey(Constant.KW_ITEST_JSON)) { this.itest_expect_json = datalist.get(Constant.KW_ITEST_JSON); datalist.remove(Constant.KW_ITEST_JSON); } parammap = datalist; this.config = config; //HttpClient HttpClient httpClient = new HttpClient(); // httpClient.setConnectionTimeout(30000); httpClient.setTimeout(30000); httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8"); PostMethod postMethod = new PostMethod(url); if (hashost == false) { //cookie copy if (config.getVariable() != null && config.getVariable().containsKey(Constant.V_CONFIG_VARIABLE_COOKIE)) { postMethod.addRequestHeader(Constant.V_CONFIG_VARIABLE_COOKIE, (String) config.getVariable().get(Constant.V_CONFIG_VARIABLE_COOKIE)); log.info("[HTTP Request Cookie]" + (String) config.getVariable().get(Constant.V_CONFIG_VARIABLE_COOKIE)); } } //??keysparams??body??key=value? if (parammap.size() == 1 && (parammap.containsKey("params") || parammap.containsKey("Params"))) { String key = ""; if (parammap.containsKey("params")) { key = "params"; } else if (parammap.containsKey("Params")) { key = "Params"; } postMethod.setRequestHeader("Content-Type", "text/json;charset=utf-8"); postMethod.setRequestBody(parammap.get(key).toString()); } else { NameValuePair[] data = new NameValuePair[parammap.size()]; int i = 0; for (Map.Entry<String, String> entry : parammap.entrySet()) { log.info("[HTTP post params]" + (String) entry.getKey() + ":" + (String) entry.getValue() + ";"); if (entry.getValue().toString().contains("###")) { } else { data[i] = new NameValuePair((String) entry.getKey(), (String) entry.getValue()); } i++; } // ?postMethod postMethod.setRequestBody(data); } Assert.assertNotNull("get request error,check the input file", postMethod); String response = ""; // postMethod try { int statusCode = httpClient.executeMethod(postMethod); // HttpClient????POSTPUT??? // 301302 if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { // ??? Header locationHeader = postMethod.getResponseHeader("location"); String location = null; if (locationHeader != null) { location = locationHeader.getValue(); log.info("The page was redirected to:" + location); } else { log.info("Location field value is null."); } } //? byte[] responseBody = postMethod.getResponseBody(); if (responseBody == null) { log.error("[HTTP response is null]:please check login or servlet"); return ""; } //?utf-8 response = new String(responseBody, "UTF-8"); //? log.info("[The Post Request's Response][" + url + "]" + response); // responseoutput File resfile = FileUtil.rewriteFile(file.getParentFile().getParent() + Constant.FILENAME_OUTPUT, file.getName().substring(0, file.getName().indexOf(".")) + ".response", response); // vargen.processProps(resfile); //?? if (this.itest_expect != null && this.itest_expect.trim().length() != 0) { Assert.assertTrue( "response different with expect:[expect]:" + this.itest_expect + "[actual]:" + response, response.contains(this.itest_expect)); } // if(this.itest_expect_json!=null&&this.itest_expect_json.trim().length()!=0){ // VerifyJsonTypeResponseImpl.verifyResponseWithJson(this.itest_expect_json,response); // // } } catch (HttpException e) { //????? log.error("Please check your provided http address!" + e.getMessage()); } catch (IOException e) { //? log.error(e.getMessage()); } catch (Exception e) { log.error("[HTTP REQUEST ERROR]:", e); //case fail throw new RuntimeException("HTTP REQUEST ERROR:" + e.getMessage()); } finally { // postMethod.releaseConnection(); } return response; }
From source file:com.zimbra.cs.dav.client.WebDavClient.java
public HttpInputStream sendPut(String href, byte[] buf, String contentType, String etag, Collection<Pair<String, String>> headers) throws IOException { boolean done = false; PutMethod put = null;//from ww w . ja va 2s . co m while (!done) { put = new PutMethod(mBaseUrl + href); put.setRequestEntity(new ByteArrayRequestEntity(buf, contentType)); if (mDebugEnabled && contentType.startsWith("text")) ZimbraLog.dav.debug("PUT payload: \n" + new String(buf, "UTF-8")); if (etag != null) put.setRequestHeader(DavProtocol.HEADER_IF_MATCH, etag); if (headers != null) for (Pair<String, String> h : headers) put.addRequestHeader(h.getFirst(), h.getSecond()); executeMethod(put, Depth.zero); int ret = put.getStatusCode(); if (ret == HttpStatus.SC_MOVED_PERMANENTLY || ret == HttpStatus.SC_MOVED_TEMPORARILY) { Header newLocation = put.getResponseHeader("Location"); if (newLocation != null) { href = newLocation.getValue(); ZimbraLog.dav.debug("redirect to new url = " + href); put.releaseConnection(); continue; } } done = true; } return new HttpInputStream(put); }
From source file:com.zimbra.cs.dav.client.WebDavClient.java
protected HttpMethod executeFollowRedirect(DavRequest req) throws IOException { HttpMethod method = null;/* w ww . ja v a 2 s .com*/ boolean done = false; while (!done) { method = execute(req); int ret = method.getStatusCode(); if (ret == HttpStatus.SC_MOVED_PERMANENTLY || ret == HttpStatus.SC_MOVED_TEMPORARILY) { Header newLocation = method.getResponseHeader("Location"); if (newLocation != null) { String uri = newLocation.getValue(); ZimbraLog.dav.debug("redirect to new url = " + uri); method.releaseConnection(); req.setRedirectUrl(uri); continue; } } done = true; } return method; }
From source file:com.celamanzi.liferay.portlets.rails286.OnlineClient.java
/** * POST// w w w . j av a2s . c o m * * Posts the parametersBody * @throws RailsAppException */ protected byte[] post(NameValuePair[] parametersBody, Map<String, Object[]> files) throws HttpException, IOException, RailsAppException { // Response body from the web server byte[] responseBody = null; statusCode = -1; List<File> tempFiles = null; HttpClient client = preparedClient(); // Create a method instance. PostMethod method = new PostMethod(requestURL.toString()); HttpMethod _method = (HttpMethod) method; String action = "POST action request URL: " + requestURL.toString(); if (ajax) { log.debug("Ajax " + action); _method.setRequestHeader("X_REQUESTED_WITH", "XMLHttpRequest"); _method.setRequestHeader("ACCEPT", "text/javascript, text/html, application/xml, text/xml, */*"); _method.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); } else log.debug(action); // finalize method method = (PostMethod) prepareMethodHeaders(_method); if (files != null && files.size() > 0) { tempFiles = new ArrayList<File>(); createMultipartRequest(parametersBody, files, method, tempFiles); } else { // Array of parameters may not be null, so init empty NameValuePair[] if (parametersBody == null) { parametersBody = new NameValuePair[0]; } method.setRequestBody(parametersBody); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); } try { // Execute the method. statusCode = client.executeMethod(method); if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY) || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || (statusCode == HttpStatus.SC_SEE_OTHER) || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) { // get Location String location = ((Header) method.getResponseHeader("Location")).getValue(); requestURL = new URL(location); log.debug("POST status code: " + method.getStatusLine()); log.debug("Redirect to location: " + location); // server may add another cookie before redirect.. cookies = client.getState().getCookies(); // Note that this GET overwrites the previous POST method, // so it should set statusCode and cookies correctly. responseBody = get(); } else { // the original POST method was OK, pass // No more redirects! Response should be 200 OK if (statusCode != HttpStatus.SC_OK) { String errorMessage = "Method failed: " + method.getStatusLine(); log.error(errorMessage); throw new RailsAppException(errorMessage, new String(method.getResponseBody())); } else { log.debug("POST status code: " + method.getStatusLine()); } // Read the response body. responseBody = method.getResponseBody(); // Keep the headers for future usage (render or resource phase) configureHeader(method.getResponseHeaders()); // Get session cookies cookies = client.getState().getCookies(); } } finally { // Release the connection method.releaseConnection(); // Delete temp files deleteFiles(tempFiles); } return responseBody; }
From source file:es.uvigo.ei.sing.jarvest.core.HTTPUtils.java
public synchronized static InputStream doPost(String urlstring, String queryString, String separator, Map<String, String> additionalHeaders, StringBuffer charsetb) throws HttpException, IOException { System.err.println("posting to: " + urlstring + ". query string: " + queryString); HashMap<String, String> query = parseQueryString(queryString, separator); HttpClient client = getClient();/*from w w w.j a v a 2s . co m*/ URL url = new URL(urlstring); int port = url.getPort(); if (port == -1) { if (url.getProtocol().equalsIgnoreCase("http")) { port = 80; } if (url.getProtocol().equalsIgnoreCase("https")) { port = 443; } } client.getHostConfiguration().setHost(url.getHost(), port, url.getProtocol()); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); final PostMethod post = new PostMethod(url.getFile()); addHeaders(additionalHeaders, post); post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); post.setRequestHeader("Accept", "*/*"); // Prepare login parameters NameValuePair[] valuePairs = new NameValuePair[query.size()]; int counter = 0; for (String key : query.keySet()) { //System.out.println("Adding pair: "+key+": "+query.get(key)); valuePairs[counter++] = new NameValuePair(key, query.get(key)); } post.setRequestBody(valuePairs); //authpost.setRequestEntity(new StringRequestEntity(requestEntity)); client.executeMethod(post); int statuscode = post.getStatusCode(); InputStream toret = null; if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header header = post.getResponseHeader("location"); if (header != null) { String newuri = header.getValue(); if ((newuri == null) || (newuri.equals(""))) { newuri = "/"; } } else { System.out.println("Invalid redirect"); System.exit(1); } } else { charsetb.append(post.getResponseCharSet()); final InputStream in = post.getResponseBodyAsStream(); toret = new InputStream() { @Override public int read() throws IOException { return in.read(); } @Override public void close() { post.releaseConnection(); } }; } return toret; }
From source file:com.dtolabs.client.utils.BaseFormAuthenticator.java
/** * Authenticate the client http state so that the colony requests can be made. * * @param baseURL URL requested for colony * @param client HttpClient instance/*from w ww. j a va2s. c om*/ * * @return true if authentication succeeded. * * @throws com.dtolabs.client.utils.HttpClientException * */ public boolean authenticate(final URL baseURL, final HttpClient client) throws HttpClientException { final HttpState state = client.getState(); if (hasSessionCookie(baseURL, state, basePath)) { return true; } final byte[] buffer = new byte[1024]; boolean doPostLogin = false; boolean isLoginFormContent = false; logger.debug("No session found, must login..."); try { final URL newUrl = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(), basePath + getInitialPath()); //load welcome page, which should forward to form based logon page. final GetMethod get = new GetMethod(newUrl.toExternalForm()); get.setDoAuthentication(false); get.setFollowRedirects(false); logger.debug("Requesting: " + newUrl); int res = client.executeMethod(get); logger.debug("Result is: " + res); /* Tomcat container auth behaves differently than Jetty. Tomcat will respond 200 OK and include the login form when auth is required, as well as on auth failure, it will also require complete GET of original URL after successful auth. Jetty will redirect to login page when auth is required, and will redirect to error page on failure. */ String body = get.getResponseBodyAsString(); if (null != body && body.contains(J_SECURITY_CHECK) && body.contains(JAVA_USER_PARAM) && body.contains(JAVA_PASS_PARAM)) { isLoginFormContent = true; } get.releaseConnection(); if ((res == HttpStatus.SC_UNAUTHORIZED)) { if (get.getResponseHeader("WWW-Authenticate") != null && get.getResponseHeader("WWW-Authenticate").getValue().matches("^Basic.*")) { logger.warn("Form-based login received UNAUTHORIZED, trying to use Basic authentication"); final BasicAuthenticator auth = new BasicAuthenticator(username, password); return auth.authenticate(baseURL, client); } else { throw new HttpClientException( "Form-based login received UNAUTHORIZED, but didn't recognize it as Basic authentication: unable to get a session"); } } //should now have the proper session cookie if (!hasSessionCookie(baseURL, state, basePath)) { throw new HttpClientException("Unable to get a session from URL : " + newUrl); } if (res == HttpStatus.SC_OK && isLoginFormContent) { doPostLogin = true; } else if ((res == HttpStatus.SC_MOVED_TEMPORARILY) || (res == HttpStatus.SC_MOVED_PERMANENTLY) || (res == HttpStatus.SC_SEE_OTHER) || (res == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header locHeader = get.getResponseHeader("Location"); if (locHeader == null) { throw new HttpClientException("Redirect with no Location header, request URL: " + newUrl); } String location = locHeader.getValue(); if (!isValidLoginRedirect(get)) { //unexpected response throw new HttpClientException("Unexpected redirection when getting session: " + location); } logger.debug("Follow redirect: " + res + ": " + location); final GetMethod redir = new GetMethod(location); redir.setFollowRedirects(true); res = client.executeMethod(redir); InputStream ins = redir.getResponseBodyAsStream(); while (ins.available() > 0) { //read and discard response body ins.read(buffer); } redir.releaseConnection(); if (res != HttpStatus.SC_OK) { throw new HttpClientException("Login page status was not OK: " + res); } logger.debug("Result: " + res); doPostLogin = true; } else if (res != HttpStatus.SC_OK) { //if request to welcome page was OK, we figure that the session is already set throw new HttpClientException("Request to welcome page returned error: " + res + ": " + get); } if (doPostLogin) { //now post login final URL loginUrl = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(), basePath + JAVA_AUTH_PATH); final PostMethod login = new PostMethod(loginUrl.toExternalForm()); login.setRequestBody(new NameValuePair[] { new NameValuePair(JAVA_USER_PARAM, getUsername()), new NameValuePair(JAVA_PASS_PARAM, getPassword()) }); login.setFollowRedirects(false); logger.debug("Post login info to URL: " + loginUrl); res = client.executeMethod(login); final InputStream ins = login.getResponseBodyAsStream(); while (ins.available() > 0) { //read and discard response body ins.read(buffer); } login.releaseConnection(); Header locHeader = login.getResponseHeader("Location"); String location = null != locHeader ? locHeader.getValue() : null; if (isLoginError(login)) { logger.error("Form-based auth failed"); return false; } else if (null != location && !location.equals(newUrl.toExternalForm())) { logger.warn("Form-based auth succeeded, but last URL was unexpected"); } if (isFollowLoginRedirect() && ((res == HttpStatus.SC_MOVED_TEMPORARILY) || (res == HttpStatus.SC_MOVED_PERMANENTLY) || (res == HttpStatus.SC_SEE_OTHER) || (res == HttpStatus.SC_TEMPORARY_REDIRECT))) { if (location == null) { throw new HttpClientException("Redirect with no Location header, request URL: " + newUrl); } final GetMethod get2 = new GetMethod(location); // logger.debug("Result: " + res + ": " + location + ", following redirect"); res = client.executeMethod(get2); } else if (res != HttpStatus.SC_OK) { throw new HttpClientException( "Login didn't seem to work: " + res + ": " + login.getResponseBodyAsString()); } logger.debug("Result: " + res); } } catch (MalformedURLException e) { throw new HttpClientException("Bad URL", e); } catch (HttpException e) { throw new HttpClientException("HTTP Error: " + e.getMessage(), e); } catch (IOException e) { throw new HttpClientException( "Error occurred while trying to authenticate to server: " + e.getMessage(), e); } return true; }
From source file:com.cerema.cloud2.lib.common.OwnCloudClient.java
public RedirectionPath followRedirection(HttpMethod method) throws IOException { int redirectionsCount = 0; int status = method.getStatusCode(); RedirectionPath result = new RedirectionPath(status, MAX_REDIRECTIONS_COUNT); while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header location = method.getResponseHeader("Location"); if (location == null) { location = method.getResponseHeader("location"); }//from ww w . ja va2 s . co m if (location != null) { Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue()); String locationStr = location.getValue(); result.addLocation(locationStr); // Release the connection to avoid reach the max number of connections per host // due to it will be set a different url exhaustResponse(method.getResponseBodyAsStream()); method.releaseConnection(); method.setURI(new URI(locationStr, true)); Header destination = method.getRequestHeader("Destination"); if (destination == null) { destination = method.getRequestHeader("destination"); } if (destination != null) { int suffixIndex = locationStr.lastIndexOf( (mCredentials instanceof OwnCloudBearerCredentials) ? AccountUtils.ODAV_PATH : AccountUtils.WEBDAV_PATH_4_0); String redirectionBase = locationStr.substring(0, suffixIndex); String destinationStr = destination.getValue(); String destinationPath = destinationStr.substring(mBaseUri.toString().length()); String redirectedDestination = redirectionBase + destinationPath; destination.setValue(redirectedDestination); method.setRequestHeader(destination); } status = super.executeMethod(method); result.addStatus(status); redirectionsCount++; } else { Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!"); status = HttpStatus.SC_NOT_FOUND; } } return result; }