Example usage for org.apache.commons.httpclient HttpStatus SC_MOVED_TEMPORARILY

List of usage examples for org.apache.commons.httpclient HttpStatus SC_MOVED_TEMPORARILY

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_MOVED_TEMPORARILY.

Prototype

int SC_MOVED_TEMPORARILY

To view the source code for org.apache.commons.httpclient HttpStatus SC_MOVED_TEMPORARILY.

Click Source Link

Document

<tt>302 Moved Temporarily</tt> (Sometimes <tt>Found</tt>) (HTTP/1.0 - RFC 1945)

Usage

From source file:com.leixl.easyframework.action.httpclient.TestHttpPost.java

public static void main(String[] args) {

    Map<String, Object> paramMap = new HashMap<String, Object>();
    paramMap.put("uid", 1);
    paramMap.put("desc",
            "?????");
    paramMap.put("payStatus", 1);

    //HttpConnUtils.postHttpContent(URL, paramMap);

    //HttpClient//from w  ww  .j  a v  a2s  . c  o m
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(URL);
    // ??
    NameValuePair[] data = { new NameValuePair("uid", "1"),
            new NameValuePair("desc",
                    "?????"),
            new NameValuePair("payStatus", "1") };
    // ?postMethod
    postMethod.setRequestBody(data);
    // postMethod
    int statusCode;
    try {
        statusCode = httpClient.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_OK) {
            StringBuffer contentBuffer = new StringBuffer();
            InputStream in = postMethod.getResponseBodyAsStream();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in, postMethod.getResponseCharSet()));
            String inputLine = null;
            while ((inputLine = reader.readLine()) != null) {
                contentBuffer.append(inputLine);
                System.out.println("input line:" + inputLine);
                contentBuffer.append("/n");
            }
            in.close();

        } else 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();
                System.out.println("The page was redirected to:" + location);
            } else {
                System.err.println("Location field value is null.");
            }
        }
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:FormLoginDemo.java

public static void main(String[] args) throws Exception {

    HttpClient client = new HttpClient();
    client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    // 'developer.java.sun.com' has cookie compliance problems
    // Their session cookie's domain attribute is in violation of the RFC2109
    // We have to resort to using compatibility cookie policy

    GetMethod authget = new GetMethod("/servlet/SessionServlet");

    client.executeMethod(authget);//w ww .j av a2s. c om
    System.out.println("Login form get: " + authget.getStatusLine().toString());
    // release any connection resources used by the method
    authget.releaseConnection();
    // See if we got any cookies
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] initcookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies());
    System.out.println("Initial set of cookies:");
    if (initcookies.length == 0) {
        System.out.println("None");
    } else {
        for (int i = 0; i < initcookies.length; i++) {
            System.out.println("- " + initcookies[i].toString());
        }
    }

    PostMethod authpost = new PostMethod("/servlet/SessionServlet");
    // Prepare login parameters
    NameValuePair action = new NameValuePair("action", "login");
    NameValuePair url = new NameValuePair("url", "/index.html");
    NameValuePair userid = new NameValuePair("UserId", "userid");
    NameValuePair password = new NameValuePair("Password", "password");
    authpost.setRequestBody(new NameValuePair[] { action, url, userid, password });

    client.executeMethod(authpost);
    System.out.println("Login form post: " + authpost.getStatusLine().toString());
    // release any connection resources used by the method
    authpost.releaseConnection();
    // See if we got any cookies
    // The only way of telling whether logon succeeded is 
    // by finding a session cookie
    Cookie[] logoncookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false,
            client.getState().getCookies());
    System.out.println("Logon cookies:");
    if (logoncookies.length == 0) {
        System.out.println("None");
    } else {
        for (int i = 0; i < logoncookies.length; i++) {
            System.out.println("- " + logoncookies[i].toString());
        }
    }
    // 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 = "/";
            }
            System.out.println("Redirect target: " + newuri);
            GetMethod redirect = new GetMethod(newuri);

            client.executeMethod(redirect);
            System.out.println("Redirect: " + redirect.getStatusLine().toString());
            // release any connection resources used by the method
            redirect.releaseConnection();
        } else {
            System.out.println("Invalid redirect");
            System.exit(1);
        }
    }
}

From source file:com.mytutorials.httpclient.FormLoginDemo.java

public static void main(String[] args) throws Exception {

    HttpClient client = new HttpClient();
    client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    // 'developer.java.sun.com' has cookie compliance problems
    // Their session cookie's domain attribute is in violation of the
    // RFC2109//from  w w  w. ja  v  a 2  s. c  o m
    // We have to resort to using compatibility cookie policy

    GetMethod authget = new GetMethod("/servlet/SessionServlet");

    client.executeMethod(authget);
    System.out.println("Login form get: " + authget.getStatusLine().toString());
    // release any connection resources used by the method
    authget.releaseConnection();
    // See if we got any cookies
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] initcookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies());
    System.out.println("Initial set of cookies:");
    if (initcookies.length == 0) {
        System.out.println("None");
    } else {
        for (int i = 0; i < initcookies.length; i++) {
            System.out.println("- " + initcookies[i].toString());
        }
    }

    PostMethod authpost = new PostMethod("/servlet/SessionServlet");
    // Prepare login parameters
    NameValuePair action = new NameValuePair("action", "login");
    NameValuePair url = new NameValuePair("url", "/index.html");
    NameValuePair userid = new NameValuePair("UserId", "userid");
    NameValuePair password = new NameValuePair("Password", "password");
    authpost.setRequestBody(new NameValuePair[] { action, url, userid, password });

    client.executeMethod(authpost);
    System.out.println("Login form post: " + authpost.getStatusLine().toString());
    // release any connection resources used by the method
    authpost.releaseConnection();
    // See if we got any cookies
    // The only way of telling whether logon succeeded is
    // by finding a session cookie
    Cookie[] logoncookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false,
            client.getState().getCookies());
    System.out.println("Logon cookies:");
    if (logoncookies.length == 0) {
        System.out.println("None");
    } else {
        for (int i = 0; i < logoncookies.length; i++) {
            System.out.println("- " + logoncookies[i].toString());
        }
    }
    // 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 = "/";
            }
            System.out.println("Redirect target: " + newuri);
            GetMethod redirect = new GetMethod(newuri);

            client.executeMethod(redirect);
            System.out.println("Redirect: " + redirect.getStatusLine().toString());
            // release any connection resources used by the method
            redirect.releaseConnection();
        } else {
            System.out.println("Invalid redirect");
            System.exit(1);
        }
    }
}

From source file:com.ms.commons.utilities.HttpClientUtils.java

public static String getResponseBodyAsString(HttpMethod method, Integer tryTimes, String responseCharSet,
        Integer maximumResponseByteSize, Integer soTimeoutMill) {
    init();// w ww .java  2  s  . co  m
    if (tryTimes == null) {
        tryTimes = 1;
    }
    if (StringUtils.isBlank(responseCharSet)) {
        responseCharSet = "utf-8";
    }
    if (maximumResponseByteSize == null) {
        maximumResponseByteSize = 50 * 1024 * 1024;
    }
    if (soTimeoutMill == null) {
        soTimeoutMill = 20000;
    }
    method.getParams().setSoTimeout(soTimeoutMill);
    InputStream httpInputStream = null;
    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) {
                if (method instanceof HttpMethodBase) {
                    responseCharSet = ((HttpMethodBase) method).getResponseCharSet();
                }
                int read = 0;
                byte[] cbuf = new byte[4096];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                httpInputStream = method.getResponseBodyAsStream();
                while ((read = httpInputStream.read(cbuf)) >= 0) {
                    baos.write(cbuf, 0, read);
                    if (baos.size() >= maximumResponseByteSize) {
                        break;
                    }
                }
                String content = baos.toString(responseCharSet);
                return content;
            }
            logger.error(String.format(
                    "getResponseBodyAsString failed, responseCode: %s, should be 200, 301, 302", responseCode));
            return "";
        } catch (Exception e) {
            logger.error("getResponseBodyAsString failed", e);
        } finally {
            IOUtils.closeQuietly(httpInputStream);
            method.releaseConnection();
        }
    }
    return "";
}

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  www  . j a va  2  s .  c  o m*/
 * 
 * @param cl the HttpClient
 * @param link the URL
 * @throws HttpStatusException
 * @throws IOException
 */
public byte[] sendGetRequest(final HttpClient cl, final String link) throws HttpStatusException, IOException {
    try {
        final GetMethod gm = new GetMethod(link);

        this.getLog().info("Downloading from Bugzilla at: " + link);

        gm.setFollowRedirects(true);

        cl.executeMethod(gm);

        final StatusLine sl = gm.getStatusLine();

        if (sl == null) {
            this.getLog().error("Unknown error validating link: " + link);

            throw new HttpStatusException("UNKNOWN STATUS");
        }

        // if we get a redirect, do so
        if (gm.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            final Header locationHeader = gm.getResponseHeader("Location");

            if (locationHeader == null) {
                this.getLog().warn("Site sent redirect, but did not set Location header");
            } else {
                final String newLink = locationHeader.getValue();

                this.getLog().debug("Following redirect to " + newLink);

                this.sendGetRequest(cl, newLink);
            }
        }

        if (gm.getStatusCode() == HttpStatus.SC_OK) {
            final InputStream is = gm.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: [" + gm.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:JiraWebSessionCallback.java

protected boolean expectRedirect(HttpMethodBase method, String page, boolean fullMatch) throws JiraException {
    if (method.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
        return false;
    }/*from  www  .java 2s  .  c o  m*/

    Header locationHeader = method.getResponseHeader("location"); //$NON-NLS-1$
    if (locationHeader == null) {
        throw new JiraRedirectException();
    }
    String url = locationHeader.getValue();
    if (fullMatch) {
        // only if followRedirects is enabled the baseUrl is guaranteed to match the redirect url, otherwise the repository might be sending back a different url 
        if ((followRedirects && !url.startsWith(baseUrl + page)) || (!followRedirects && !url.endsWith(page))) {
            throw new JiraRedirectException(url);
        }
    } else {
        // the client does not know exactly where the repository will redirect to
        if (!url.contains(page)) {
            throw new JiraRedirectException(url);
        }
    }
    return true;
}

From source file:com.wafersystems.util.HttpUtil.java

/**
 * ??//from w  ww.  ja va  2  s  .co m
 * 
 * @param ip         IP?
 * @param port         ??
 * @param hClient      HttpClient
 * @param method      HttpMethod
 * @param lastResult   
 * 
 * @return
 */
public static int checkRedirect(String ip, int port, HttpClient hClient, HttpMethod method, int lastResult)
        throws Exception {
    int result = HttpStatus.SC_OK;

    if ((lastResult == HttpStatus.SC_MOVED_TEMPORARILY) || (lastResult == HttpStatus.SC_MOVED_PERMANENTLY)
            || (lastResult == HttpStatus.SC_SEE_OTHER) || (lastResult == HttpStatus.SC_TEMPORARY_REDIRECT)) {
        //????URL?
        Header header = method.getResponseHeader("location");
        if (header != null) {
            String newURI = header.getValue();
            if (StrUtil.isEmptyStr(newURI))
                newURI = "http://" + ip + ":" + port + "/";

            //URL??IP??
            if (!newURI.startsWith("http"))
                newURI = "http://" + ip + ":" + port + newURI;
            logger.warn("??" + newURI);
            method = new GetMethod(newURI);
            result = hClient.executeMethod(method);
        }
    }

    return result;
}

From source file:com.mirth.connect.client.core.ConnectServiceUtil.java

public static void registerUser(String serverId, String mirthVersion, User user, String[] protocols,
        String[] cipherSuites) throws ClientException {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;
    NameValuePair[] params = { new BasicNameValuePair("serverId", serverId),
            new BasicNameValuePair("version", mirthVersion),
            new BasicNameValuePair("user", ObjectXMLSerializer.getInstance().serialize(user)) };

    HttpPost post = new HttpPost();
    post.setURI(URI.create(URL_CONNECT_SERVER + URL_REGISTRATION_SERVLET));
    post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8")));
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT)
            .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();

    try {/* w w  w  . j a v  a2  s  .  c om*/
        HttpClientContext postContext = HttpClientContext.create();
        postContext.setRequestConfig(requestConfig);
        httpClient = getClient(protocols, cipherSuites);
        httpResponse = httpClient.execute(post, postContext);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_MOVED_TEMPORARILY)) {
            throw new Exception("Failed to connect to update server: " + statusLine);
        }
    } catch (Exception e) {
        throw new ClientException(e);
    } finally {
        HttpClientUtils.closeQuietly(httpResponse);
        HttpClientUtils.closeQuietly(httpClient);
    }
}

From source file:net.sf.xmm.moviemanager.http.HttpUtil.java

public boolean setUpIMDbAuthentication() {

    if (httpSettings == null) {
        log.warn("Authentication could not be set. Missing authentication settings.");
        return false;
    }//  www.  ja  v  a 2s  .c om

    if (httpSettings.getIMDbAuthenticationEnabled()) {

        try {

            if (!isSetup())
                setup();

            client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

            PostMethod postMethod = new PostMethod(("https://secure.imdb.com/register-imdb/login"));

            NameValuePair[] postData = new NameValuePair[2];
            postData[0] = new NameValuePair("login", httpSettings.getIMDbAuthenticationUser());
            postData[1] = new NameValuePair("password", httpSettings.getIMDbAuthenticationPassword());

            postMethod.setRequestBody(postData);

            int statusCode = client.executeMethod(postMethod);

            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
                imdbAuthenticationSetUp = true;
            else
                imdbAuthenticationSetUp = false;

        } catch (Exception e) {
            log.warn("error:" + e.getMessage());
        }
    } else
        imdbAuthenticationSetUp = false;

    return imdbAuthenticationSetUp;
}

From source file:au.com.permeance.liferay.portlet.documentlibrary.action.DownloadFolderZipAction.java

@Override
public void serveResource(StrutsPortletAction originalStrutsPortletAction, PortletConfig portletConfig,
        ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws Exception {

    long repositoryId = ParamUtil.getLong(resourceRequest, "repositoryId");
    long folderId = ParamUtil.getLong(resourceRequest, "folderId");

    try {//from w ww .j a  v a 2  s  . c om

        downloadFolder(resourceRequest, resourceResponse);

    } catch (Exception e) {

        String msg = "Error downloading folder " + folderId + " from repository " + repositoryId + " : "
                + e.getMessage();
        s_log.error(msg, e);

        SessionErrors.add(resourceRequest, e.getClass().getName());
        resourceResponse.setProperty(ResourceResponse.HTTP_STATUS_CODE, "" + HttpStatus.SC_MOVED_TEMPORARILY);
        resourceResponse.addProperty("Location", resourceResponse.createRenderURL().toString());

    }
}