Example usage for java.net HttpURLConnection HTTP_MOVED_TEMP

List of usage examples for java.net HttpURLConnection HTTP_MOVED_TEMP

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_MOVED_TEMP.

Prototype

int HTTP_MOVED_TEMP

To view the source code for java.net HttpURLConnection HTTP_MOVED_TEMP.

Click Source Link

Document

HTTP Status-Code 302: Temporary Redirect.

Usage

From source file:org.jboss.test.web.test.FormAuthUnitTestCase.java

/** Test that a post from an unsecured form to a secured servlet does not
 * loose its data during the redirct to the form login.
 * /*from  w  w w . j  ava  2 s.co m*/
 * @throws Exception
 */
public void testPostDataFormAuth() throws Exception {
    log.info("+++ testPostDataFormAuth");
    // Start by accessing the secured index.html of war1
    HttpClient httpConn = new HttpClient();
    GetMethod indexGet = new GetMethod(baseURLNoAuth + "form-auth/unsecure_form.html");
    int responseCode = httpConn.executeMethod(indexGet);
    assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
    // Submit the form to /restricted/SecuredPostServlet
    PostMethod servletPost = new PostMethod(baseURLNoAuth + "form-auth/restricted/SecuredPostServlet");
    servletPost.addParameter("checkParam", "123456");
    responseCode = httpConn.executeMethod(servletPost);

    String body = servletPost.getResponseBodyAsString();
    assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
    assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0);

    HttpState state = httpConn.getState();
    Cookie[] cookies = state.getCookies();
    String sessionID = null;
    for (int c = 0; c < cookies.length; c++) {
        Cookie k = cookies[c];
        if (k.getName().equalsIgnoreCase("JSESSIONID"))
            sessionID = k.getValue();
    }
    getLog().debug("Saw JSESSIONID=" + sessionID);
    // Submit the login form
    PostMethod formPost = new PostMethod(baseURLNoAuth + "form-auth/j_security_check");
    formPost.addRequestHeader("Referer", baseURLNoAuth + "form-auth/unsecure_form.html");
    formPost.addParameter("j_username", "jduke");
    formPost.addParameter("j_password", "theduke");
    responseCode = httpConn.executeMethod(formPost.getHostConfiguration(), formPost, state);
    String response = formPost.getStatusText();
    getLog().debug("responseCode=" + responseCode + ", response=" + response);
    assertTrue("Saw HTTP_MOVED_TEMP", responseCode == HttpURLConnection.HTTP_MOVED_TEMP);

    //  Follow the redirect to the SecureServlet
    Header location = formPost.getResponseHeader("Location");
    String indexURI = location.getValue();
    GetMethod war1Index = new GetMethod(indexURI);
    responseCode = httpConn.executeMethod(war1Index.getHostConfiguration(), war1Index, state);
    assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
    body = war1Index.getResponseBodyAsString();
    if (body.indexOf("j_security_check") > 0)
        fail("get of " + indexURI + " redirected to login page");
}

From source file:net.praqma.jenkins.rqm.request.RQMHttpClient.java

public void followRedirects(HttpMethodBase method, int responseCode) throws HttpException, IOException {
    Header location = method.getResponseHeader("Location");
    while (location != null && responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
        GetMethod get3 = new GetMethod(location.getValue());
        responseCode = executeMethod(get3);
        if (responseCode != HttpURLConnection.HTTP_OK) {
            log.fine(String.format("Follow redirects returned code %s", responseCode));
        }/*from   w  w w  . j  ava2  s .  co m*/
        location = get3.getResponseHeader("Location");

    }
}

From source file:edu.hackathon.perseus.core.httpSpeedTest.java

public static String getRedirectUrl(REGION region) {
    String result = "";

    switch (region) {
    case EU://from   w w  w .jav  a 2s  .  c  o  m
        result = amazonEuDomain;
        break;
    case USA:
        result = amazonUsaDomain;
        break;
    case ASIA:
        result = amazonAsiaDomain;
        break;
    }

    System.out.println("Trying to get real IP address of " + result);
    try {
        /*
        HttpHead headRequest = new HttpHead(result);
        HttpClient client = new DefaultHttpClient();
         HttpResponse response = client.execute(headRequest);
         final int statusCode = response.getStatusLine().getStatusCode();
         if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
             statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
         {
             String location = response.getHeaders("Location")[0].toString();
             String redirecturl = location.replace("Location: ", "");
             result = redirecturl;
         }
        */

        URL url = new URL(result);
        HttpURLConnection httpGetCon = (HttpURLConnection) url.openConnection();
        httpGetCon.setInstanceFollowRedirects(false);
        httpGetCon.setRequestMethod("GET");
        httpGetCon.setConnectTimeout(5000); //set timeout to 5 seconds

        httpGetCon.setRequestProperty("User-Agent", USER_AGENT);

        int status = httpGetCon.getResponseCode();
        System.out.println("code: " + status);
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER)
            result = httpGetCon.getHeaderField("Location");

    } catch (Exception e) {
        System.out.println("Exception is fired in redirector getter. error:" + e.getMessage());
        e.printStackTrace();
    }
    System.out.println("Real IP address is " + result);
    return result;
}

From source file:mobi.jenkinsci.alm.assembla.client.AssemblaClient.java

private Document postLoginForm(final Document pinDoc) throws IOException {
    final List<NameValuePair> formNvps = new ArrayList<NameValuePair>();
    final Element form = pinDoc.select("form[id=login-box]").first();
    final String formAction = form.attr("action");
    final HttpPost formPost = new HttpPost(getUrl(formAction).toString());
    final Elements formFields = form.select("input");
    for (final Element element : formFields) {
        final String fieldName = element.attr("name");
        String fieldValue = element.attr("value");
        final String fieldId = element.attr("id");
        final String fieldType = element.attr("type");

        if (fieldId.equalsIgnoreCase("user_login")) {
            fieldValue = username;//from   w  w  w .ja  v a  2 s.c  om
            ;
        } else if (fieldId.equalsIgnoreCase("user_password")) {
            fieldValue = password;
        }

        if (fieldType.equals("submit")) {
            if (!fieldName.equalsIgnoreCase("commit")) {
                continue;
            }
        }

        LOG.debug(String.format("Processing form field: name='%s' value='%s' id='%s'", fieldName, fieldValue,
                fieldId));
        formNvps.add(new BasicNameValuePair(fieldName, fieldValue));
    }
    try {
        formPost.setEntity(new UrlEncodedFormEntity(formNvps, "UTF-8"));
    } catch (final UnsupportedEncodingException e) {
        // This would never happen
        throw new IllegalArgumentException("UTF-8 not recognised");
    }

    HttpResponse response;
    LOG.debug("Login via posting form-data to " + formPost.getURI());
    try {
        response = sendHttpPost(formPost);
        if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_MOVED_TEMP) {
            throw new IOException("Form-based login to Assembla failed: " + response.getStatusLine());
        }
        return Jsoup.parse(getData(response.getFirstHeader("Location").getValue(), false));
    } finally {
        formPost.releaseConnection();
    }
}

From source file:mobi.jenkinsci.ci.client.JenkinsClient.java

public AbstractNode execute(final String command) throws IOException {
    final HttpPost post = new HttpPost(getCommandUrl(command));
    try {//from w w  w  .ja  v  a 2  s.  c  o  m
        final HttpResponse response = http.execute(post);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_MOVED_PERM
                || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) {
            return new ResetNode();
        } else {
            throw new IOException(
                    "Command " + command + " *FAILED* with HTTP Status " + response.getStatusLine());
        }
    } finally {
        post.releaseConnection();
    }
}

From source file:be.cytomine.client.HttpClient.java

public BufferedImage readBufferedImageFromURL(String url) throws IOException {
    log.debug("readBufferedImageFromURL:" + url);
    URL URL = new URL(url);
    HttpHost targetHost = new HttpHost(URL.getHost(), URL.getPort());
    log.debug("targetHost:" + targetHost);
    DefaultHttpClient client = new DefaultHttpClient();

    log.debug("client:" + client);
    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    log.debug("localcontext:" + localcontext);

    headersArray = null;/* w  w w .  j av  a  2  s  .  c  o m*/
    authorize("GET", URL.toString(), "", "application/json,*/*");

    BufferedImage img = null;
    HttpGet httpGet = new HttpGet(URL.toString());
    httpGet.setHeaders(headersArray);
    HttpResponse response = client.execute(targetHost, httpGet, localcontext);

    int code = response.getStatusLine().getStatusCode();
    log.info("url=" + url + " is " + code + "(OK=" + HttpURLConnection.HTTP_OK + ",MOVED="
            + HttpURLConnection.HTTP_MOVED_TEMP + ")");

    boolean isOK = (code == HttpURLConnection.HTTP_OK);
    boolean isFound = (code == HttpURLConnection.HTTP_MOVED_TEMP);
    boolean isErrorServer = (code == HttpURLConnection.HTTP_INTERNAL_ERROR);

    if (!isOK && !isFound & !isErrorServer)
        throw new IOException(url + " cannot be read: " + code);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        img = ImageIO.read(entity.getContent());
    }
    return img;

}

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

public void collect() {
    if (isPingCompat.get()) {
        // back compat w/ old url.availability templates
        super.collect();
        return;//from   ww w.  j  a v a 2s  . c  om
    }
    this.matches.clear();
    HttpConfig config = new HttpConfig(getTimeoutMillis(), getTimeoutMillis(), proxyHost.get(),
            proxyPort.get());
    AgentKeystoreConfig keystoreConfig = new AgentKeystoreConfig();
    log.debug("isAcceptUnverifiedCert:" + keystoreConfig.isAcceptUnverifiedCert());
    HQHttpClient client = new HQHttpClient(keystoreConfig, config, keystoreConfig.isAcceptUnverifiedCert());
    HttpParams params = client.getParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, useragent.get());
    if (this.hosthdr != null) {
        params.setParameter(ClientPNames.VIRTUAL_HOST, this.hosthdr);
    }
    HttpRequestBase request;
    double avail = 0;
    try {
        if (getMethod().equals(HttpHead.METHOD_NAME)) {
            request = new HttpHead(getURL());
            addParams(request, this.params.get());
        } else if (getMethod().equals(HttpPost.METHOD_NAME)) {
            HttpPost httpPost = new HttpPost(getURL());
            request = httpPost;
            addParams(httpPost, this.params.get());
        } else {
            request = new HttpGet(getURL());
            addParams(request, this.params.get());
        }
        request.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, isFollow());
        addCredentials(request, client);
        startTime();
        HttpResponse response = client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        int tries = 0;
        while (statusCode == HttpURLConnection.HTTP_MOVED_TEMP && tries < 3) {
            tries++;
            Header header = response.getFirstHeader("Location");
            String url = header.getValue();
            String[] toks = url.split(";");
            String[] t = toks.length > 1 ? toks[1].split("\\?") : new String[0];
            response = getRedirect(toks[0], t.length > 1 ? t[1] : "");
            statusCode = response.getStatusLine().getStatusCode();
        }
        endTime();
        setResponseCode(statusCode);
        avail = getAvail(statusCode);
        StringBuilder msg = new StringBuilder(String.valueOf(statusCode));
        Header header = response.getFirstHeader("Server");
        msg.append(header != null ? " (" + header.getValue() + ")" : "");
        setLastModified(response, statusCode);
        avail = checkPattern(response, avail, msg);
        setAvailMsg(avail, msg);
    } catch (UnsupportedEncodingException e) {
        log.error("unsupported encoding: " + e, e);
    } catch (IOException e) {
        avail = Metric.AVAIL_DOWN;
        setErrorMessage(e.toString());
    } finally {
        setAvailability(avail);
    }
    netstat();
}

From source file:org.jboss.test.web.test.FormAuthUnitTestCase.java

public PostMethod doSecureGetWithLogin(String path, String username, String password) throws Exception {
    GetMethod indexGet = new GetMethod(baseURLNoAuth + path);
    int responseCode = httpConn.executeMethod(indexGet);
    String body = indexGet.getResponseBodyAsString();
    assertTrue("Get OK(" + responseCode + ")", responseCode == HttpURLConnection.HTTP_OK);
    assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0);

    HttpState state = httpConn.getState();
    Cookie[] cookies = state.getCookies();
    String sessionID = null;//  www  . j  a  v  a  2s .  c  o m
    for (int c = 0; c < cookies.length; c++) {
        Cookie k = cookies[c];
        if (k.getName().equalsIgnoreCase("JSESSIONID"))
            sessionID = k.getValue();
    }
    getLog().debug("Saw JSESSIONID=" + sessionID);

    // Submit the login form
    PostMethod formPost = new PostMethod(baseURLNoAuth + "form-auth/j_security_check");
    formPost.addRequestHeader("Referer", baseURLNoAuth + "form-auth/restricted/login.html");
    formPost.addParameter("j_username", username);
    formPost.addParameter("j_password", password);
    responseCode = httpConn.executeMethod(formPost.getHostConfiguration(), formPost, state);
    String response = formPost.getStatusText();
    log.debug("responseCode=" + responseCode + ", response=" + response);
    assertTrue("Saw HTTP_MOVED_TEMP", responseCode == HttpURLConnection.HTTP_MOVED_TEMP);

    //  Follow the redirect to the SecureServlet
    Header location = formPost.getResponseHeader("Location");
    String indexURI = location.getValue();
    GetMethod war1Index = new GetMethod(indexURI);
    responseCode = httpConn.executeMethod(war1Index.getHostConfiguration(), war1Index, state);
    response = war1Index.getStatusText();
    log.debug("responseCode=" + responseCode + ", response=" + response);
    assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
    body = war1Index.getResponseBodyAsString();
    if (body.indexOf("j_security_check") > 0)
        fail("get of " + indexURI + " redirected to login page");
    return formPost;
}

From source file:be.cytomine.client.HttpClient.java

public static BufferedImage readBufferedImageFromPOST(String url, String post) throws IOException {
    log.debug("readBufferedImageFromURL:" + url);
    URL URL = new URL(url);
    HttpHost targetHost = new HttpHost(URL.getHost(), URL.getPort());
    log.debug("targetHost:" + targetHost);
    DefaultHttpClient client = new DefaultHttpClient();

    log.debug("client:" + client);
    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    log.debug("localcontext:" + localcontext);

    BufferedImage img = null;//from w  w w  .ja  va  2s .  co m
    HttpPost httpPost = new HttpPost(URL.toString());
    httpPost.setEntity(new StringEntity(post, "UTF-8"));
    HttpResponse response = client.execute(targetHost, httpPost, localcontext);

    int code = response.getStatusLine().getStatusCode();
    log.info("url=" + url + " is " + code + "(OK=" + HttpURLConnection.HTTP_OK + ",MOVED="
            + HttpURLConnection.HTTP_MOVED_TEMP + ")");

    boolean isOK = (code == HttpURLConnection.HTTP_OK);
    boolean isFound = (code == HttpURLConnection.HTTP_MOVED_TEMP);
    boolean isErrorServer = (code == HttpURLConnection.HTTP_INTERNAL_ERROR);

    if (!isOK && !isFound & !isErrorServer)
        throw new IOException(url + " cannot be read: " + code);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        img = ImageIO.read(entity.getContent());
    }
    return img;
}

From source file:vocab.VocabUtils.java

/**
 * Jena fails to load models in https with content negotiation. Therefore I do
 * the negotiation here directly//from   ww w .  j  a v a2  s  . co  m
 */
private static void doContentNegotiation(OntModel model, Vocabulary v, String accept, String serialization) {
    try {
        model.read(v.getUri(), null, serialization);

    } catch (Exception e) {
        try {
            System.out.println("Failed to read the ontology. Doing content negotiation");
            URL url = new URL(v.getUri());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Accept", accept);

            int status = connection.getResponseCode();
            if (status == HttpURLConnection.HTTP_SEE_OTHER || status == HttpURLConnection.HTTP_MOVED_TEMP
                    || status == HttpURLConnection.HTTP_MOVED_PERM) {
                String newUrl = connection.getHeaderField("Location");
                //v.setUri(newUrl);
                connection = (HttpURLConnection) new URL(newUrl).openConnection();
                connection.setRequestProperty("Accept", accept);
                InputStream in = (InputStream) connection.getInputStream();
                model.read(in, null, serialization);
            }
        } catch (Exception e2) {
            System.out.println("Failed to read the ontology");
        }
    }
}