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

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

Introduction

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

Prototype

int SC_TEMPORARY_REDIRECT

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

Click Source Link

Document

<tt>307 Temporary Redirect</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. j a v a 2  s. 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/*  w  w  w.j  a va2s .  co  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.wafersystems.util.HttpUtil.java

/**
 * ??//from  w  w  w . j a  v a 2  s .c om
 * 
 * @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:net.sourceforge.jwbf.actions.HttpActionClient.java

/**
 * Process a POST Message./* w  w  w .ja  va2 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: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");
        }/*  w  w w  .  ja  va2 s  . c o  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.djimenez.tuenti.example.FormLoginDemo.java

/**
 * @param client/*from  w w  w  . j  a v  a  2  s  . 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 a  v a2  s.co  m
        return false;
    }
}

From source file:com.tops.hotelmanager.util.CommonHttpClient.java

private static String executePOSTRequestV1(String url, Map<String, Object> requestData,
        Map<String, String> headerMap, String contentType, int timeOut, int retry) {
    PostMethod post = new PostMethod(url);
    Gson gson = new Gson();
    String errorMsg = "error~Request Failed";
    try {/*w  w  w .  j  a va2  s .c  o  m*/
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setSoTimeout(timeOut);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(timeOut);
        if (requestData == null || requestData.isEmpty()) {
            throw new CustomException("Request data is null");
        }
        if (contentType != null && contentType.equals(CommonHttpClient.CONTENT_TYPE_JSON)) {
            StringRequestEntity requestEntity = new StringRequestEntity(gson.toJson(requestData), contentType,
                    "UTF-8");
            post.setRequestEntity(requestEntity);
        } else {
            // SET REQUEST PARAMETER
            for (Map.Entry<String, Object> entry : requestData.entrySet()) {
                post.addParameter(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }
        // SET REQUEST HEADER
        if (headerMap != null) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                post.addRequestHeader(entry.getKey(), entry.getValue());
            }
        }
        int status = client.executeMethod(post);
        // System.out.println("URL:" + url);
        // System.out.println("\n REQUEST HEADERS:");
        // Header[] requestHeaders = post.getRequestHeaders();
        // for (Header header : requestHeaders) {
        // System.out.println(header.getName() + "=" + header.getValue());
        // }
        // System.out.println("\n RESPONSE HEADERS:");
        // Header[] responseHeaders = post.getResponseHeaders();
        // for (Header header : responseHeaders) {
        // System.out.println(header.getName() + "=" + header.getValue());
        // }
        // System.out.println(post.getStatusText());
        // System.out.println(post.getStatusLine().getReasonPhrase());
        // System.out.println(post.getResponseBodyAsString());
        if (status == HttpStatus.SC_OK) {
            return post.getResponseBodyAsString();
        } else if (status == HttpStatus.SC_TEMPORARY_REDIRECT) {
            Header header = post.getResponseHeader("Location");
            if (retry != 1) {
                errorMsg = executePOSTRequestV1(header.getValue(), requestData, headerMap, contentType, timeOut,
                        retry++);
            }
        } else {
            errorMsg += ",HttpStatus:" + status;
        }
    } catch (Exception ex) {
        logger.error("executePOSTRequestV1 url: " + url + ", Parameters: " + requestData, ex);
        errorMsg = errorMsg + ":" + ex.getMessage();
    } finally {
        post.releaseConnection();
    }
    return errorMsg;
}

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 .  ja va2 s .c  o 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/* ww  w  .ja v a2 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;
}