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

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

Introduction

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

Prototype

int SC_SEE_OTHER

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

Click Source Link

Document

<tt>303 See Other</tt> (HTTP/1.1 - RFC 2616)

Usage

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);//from  w ww.  ja  va 2 s  . c o  m
    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. j  a v  a2s .c om
    // 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.wafersystems.util.HttpUtil.java

/**
 * ??// ww w . j a  v a 2  s. com
 * 
 * @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.zimbra.cs.store.triton.TritonIncomingOutputStream.java

private void sendHttpData() throws IOException {
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    PostMethod post;/*  w  w w  . j av  a2  s .  c o  m*/
    boolean started = false;
    if (uploadUrl.isInitialized()) {
        started = true;
        post = new PostMethod(baseUrl + uploadUrl);
    } else {
        post = new PostMethod(baseUrl + "/blob");
    }
    try {
        ZimbraLog.store.info("posting to %s", post.getURI());
        HttpClientUtil.addInputStreamToHttpMethod(post, new ByteArrayInputStream(baos.toByteArray()),
                baos.size(), "application/octet-stream");
        post.addRequestHeader(TritonHeaders.CONTENT_LENGTH, baos.size() + "");
        post.addRequestHeader(TritonHeaders.HASH_TYPE, hashType.toString());
        post.addRequestHeader("Content-Range",
                "bytes " + written.longValue() + "-" + (written.longValue() + baos.size() - 1) + "/*");
        if (serverToken.getToken() != null) {
            post.addRequestHeader(TritonHeaders.SERVER_TOKEN, serverToken.getToken());
        }
        int statusCode = HttpClientUtil.executeMethod(client, post);
        if (statusCode == HttpStatus.SC_OK) {
            handleResponse(post);
        } else if (!started && statusCode == HttpStatus.SC_SEE_OTHER) {
            started = true;
            uploadUrl.setUploadUrl(post.getResponseHeader(TritonHeaders.LOCATION).getValue());
            handleResponse(post);
        } else {
            throw new IOException("Unable to append, bad response code " + statusCode);
        }
    } finally {
        post.releaseConnection();
    }
    baos = new ByteArrayOutputStream(LC.triton_upload_buffer_size.intValue());
}

From source file:net.sourceforge.jwbf.actions.HttpActionClient.java

/**
 * Process a POST Message./*from   w w w  . j  a  v a2s.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.djimenez.tuenti.example.FormLoginDemo.java

/**
 * @param client/*from  w  w  w  .ja v  a2s  . co m*/
 * @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: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 w  w w.j  av a 2 s  .c om
        return false;
    }
}

From source file:de.mpg.escidoc.services.tools.scripts.person_grants.Util.java

/**
 * Logs in the given user with the given password.
 * //from   www. jav  a2s  . c om
 * @param userid The id of the user to log in.
 * @param password The password of the user to log in.
 * @return The handle for the logged in user.
 * @throws HttpException
 * @throws IOException
 * @throws ServiceException
 * @throws URISyntaxException
 */
public static String loginUser(String userid, String password, String frameworkUrl)
        throws HttpException, IOException, ServiceException, URISyntaxException {
    int delim1 = frameworkUrl.indexOf("//");
    int delim2 = frameworkUrl.indexOf(":", delim1);
    String host;
    int port;
    if (delim2 > 0) {
        host = frameworkUrl.substring(delim1 + 2, delim2);
        port = Integer.parseInt(frameworkUrl.substring(delim2 + 1));
    } else {
        host = frameworkUrl.substring(delim1 + 2);
        port = 80;
    }
    HttpClient client = new HttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check");
    login.addParameter("j_username", userid);
    login.addParameter("j_password", password);
    client.executeMethod(login);
    login.releaseConnection();
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    //        Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies());
    Cookie sessionCookie = client.getState().getCookies()[0];
    PostMethod postMethod = new PostMethod(frameworkUrl + "/aa/login");
    postMethod.addParameter("target", frameworkUrl);
    client.getState().addCookie(sessionCookie);
    client.executeMethod(postMethod);
    if (HttpStatus.SC_SEE_OTHER != postMethod.getStatusCode()) {
        throw new HttpException("Wrong status code: " + login.getStatusCode());
    }
    String userHandle = null;
    Header headers[] = postMethod.getResponseHeaders();
    for (int i = 0; i < headers.length; ++i) {
        if ("Location".equals(headers[i].getName())) {
            String location = headers[i].getValue();
            int index = location.indexOf('=');
            userHandle = new String(Base64.decode(location.substring(index + 1, location.length())));
            // System.out.println("location: "+location);
            // System.out.println("handle: "+userHandle);
        }
    }
    if (userHandle == null) {
        throw new ServiceException("User not logged in.");
    }
    return userHandle;
}

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  2 s . 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.celamanzi.liferay.portlets.rails286.OnlineClient.java

/** 
 * POST//from w w w.  j av  a 2 s.  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;
}