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:net.praqma.jenkins.rqm.request.RQMHttpClient.java

public int login() throws HttpException, IOException, GeneralSecurityException {
    log.finest("Register trusting ssl");
    registerTrustingSSL();/*from www .ja va 2  s.c om*/

    GetMethod methodPart1 = new GetMethod(url.toString() + contextRoot + "/auth/authrequired");

    int response = executeMethod(methodPart1);

    followRedirects(methodPart1, response);

    GetMethod methodPart2 = new GetMethod(this.url.toString() + contextRoot + "/authenticated/identity");

    response = executeMethod(methodPart2);

    followRedirects(methodPart2, response);

    HttpMethodBase authenticationMethod = null;
    Header authenticateHeader = methodPart2.getResponseHeader("WWW-Authenticate"); //$NON-NLS-1$

    if ((response == HttpURLConnection.HTTP_UNAUTHORIZED) && (authenticateHeader != null)
            && (authenticateHeader.getValue().toLowerCase().indexOf("basic realm") == 0)) {

        super.getState().setCredentials(new AuthScope(host, port),
                new UsernamePasswordCredentials(getUsr(), getPassword()));

        String authMethod = this.url.toString() + "/authenticated/identity";
        authenticationMethod = new GetMethod(authMethod);
        response = super.executeMethod(methodPart2);
    } else {
        authenticationMethod = new PostMethod(this.url.toString() + contextRoot + "/j_security_check");
        NameValuePair[] nvps = new NameValuePair[2];
        nvps[0] = new NameValuePair("j_username", getUsr());
        nvps[1] = new NameValuePair("j_password", getPassword());
        ((PostMethod) (authenticationMethod)).addParameters(nvps);
        ((PostMethod) (authenticationMethod)).addRequestHeader("Content-Type",
                "application/x-www-form-urlencoded; charset=utf-8");
        response = executeMethod(authenticationMethod);
        Header location = authenticationMethod.getResponseHeader("X-com-ibm-team-repository-web-auth-msg");
        if (location != null && location.getValue().indexOf("authfailed") >= 0) {
            response = HttpURLConnection.HTTP_UNAUTHORIZED;
        }
    }

    if ((response != HttpURLConnection.HTTP_OK) && (response != HttpURLConnection.HTTP_MOVED_TEMP)) {
        if (response != HttpURLConnection.HTTP_UNAUTHORIZED) {
            String body = "";
            try {
                body = authenticationMethod.getResponseBodyAsString();
            } catch (Exception e) {
                log.severe(String.format("Failed to login, with response code %s %n Response body: %n %s",
                        response, body));
            }
            log.severe(String.format("Failed to login, with response code %s %n Response body: %n %s", response,
                    body));
        }
    } else {
        followRedirects(authenticationMethod, response);
        String methodText = String.format(
                "%s%s/service/com.ibm.team.repository.service.internal.webuiInitializer.IWebUIInitializerRestService/initializationData",
                url.toString(), contextRoot);
        GetMethod get3 = new GetMethod(methodText);
        response = executeMethod(get3);
        followRedirects(get3, response);
    }

    log.finest("Response was: " + response);
    return response;
}

From source file:com.github.dozermapper.core.builder.xml.SchemaLSResourceResolver.java

/**
 * Attempts to open a http connection for the systemId resource, and follows the first redirect
 *
 * @param systemId url to the XSD/* w  w  w.j  a va 2  s.  c  o m*/
 * @return stream to XSD
 * @throws IOException if fails to find XSD
 */
private InputStream resolveFromURL(String systemId) throws IOException {
    LOG.debug("Trying to download [{}]", systemId);

    URL obj = new URL(systemId);
    HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

    int status = conn.getResponseCode();
    if ((status != HttpURLConnection.HTTP_OK) && (status == HttpURLConnection.HTTP_MOVED_TEMP
            || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER)) {

        LOG.debug("Received status of {}, attempting to follow Location header", status);

        String newUrl = conn.getHeaderField("Location");
        conn = (HttpURLConnection) new URL(newUrl).openConnection();
    }

    return conn.getInputStream();
}

From source file:org.jboss.as.test.integration.web.sso.SSOTestBase.java

public static void executeFormLogin(HttpClient httpConn, URL warURL) throws IOException {
    // Submit the login form
    HttpPost formPost = new HttpPost(warURL + "j_security_check");
    formPost.addHeader("Referer", warURL + "login.html");

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("j_username", "user1"));
    formparams.add(new BasicNameValuePair("j_password", "password1"));
    formPost.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));

    HttpResponse postResponse = httpConn.execute(formPost);

    int statusCode = postResponse.getStatusLine().getStatusCode();
    Header[] errorHeaders = postResponse.getHeaders("X-NoJException");
    assertTrue("Should see HTTP_MOVED_TEMP. Got " + statusCode,
            statusCode == HttpURLConnection.HTTP_MOVED_TEMP);
    assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
    EntityUtils.consume(postResponse.getEntity());

    // Follow the redirect to the index.html page
    String indexURL = postResponse.getFirstHeader("Location").getValue();
    HttpGet rediretGet = new HttpGet(indexURL.toString());
    HttpResponse redirectResponse = httpConn.execute(rediretGet);

    statusCode = redirectResponse.getStatusLine().getStatusCode();
    errorHeaders = redirectResponse.getHeaders("X-NoJException");
    assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);

    String body = EntityUtils.toString(redirectResponse.getEntity());
    assertTrue("Get of " + indexURL + " redirected to login page", body.indexOf("j_security_check") < 0);
}

From source file:it.user.OAuth2IdentityProviderTest.java

private void simulateRedirectionToCallback() {
    fakeServerAuthProvider.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
            .addHeader(/*from w ww .  j ava  2 s  .  c  om*/
                    "Location: " + ORCHESTRATOR.getServer().getUrl() + "/oauth2/callback/" + FAKE_PROVIDER_KEY)
            .setBody("Redirect to SonarQube"));
}

From source file:net.mceoin.cominghome.api.NestUtil.java

private static String getNestAwayStatusCall(String access_token) {

    String away_status = "";

    String urlString = "https://developer-api.nest.com/structures?auth=" + access_token;
    log.info("url=" + urlString);

    StringBuilder builder = new StringBuilder();
    boolean error = false;
    String errorResult = "";

    HttpURLConnection urlConnection = null;
    try {/* w  w  w  .ja  v a  2  s  .c o  m*/
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0");
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setConnectTimeout(15000);
        urlConnection.setReadTimeout(15000);
        //            urlConnection.setChunkedStreamingMode(0);

        //            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");

        boolean redirect = false;

        // normally, 3xx is redirect
        int status = urlConnection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == 307 // Temporary redirect
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        //            System.out.println("Response Code ... " + status);

        if (redirect) {

            // get redirect url from "location" header field
            String newUrl = urlConnection.getHeaderField("Location");

            // open the new connnection again
            urlConnection = (HttpURLConnection) new URL(newUrl).openConnection();
            urlConnection.setRequestMethod("PUT");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            //                urlConnection.setChunkedStreamingMode(0);

            //                System.out.println("Redirect to URL : " + newUrl);

        }

        int statusCode = urlConnection.getResponseCode();

        log.info("statusCode=" + statusCode);
        if ((statusCode == HttpURLConnection.HTTP_OK)) {
            error = false;

            InputStream response;
            response = urlConnection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                JSONObject structure = object.getJSONObject(key);

                if (structure.has("away")) {
                    away_status = structure.getString("away");
                } else {
                    log.info("missing away");
                }
            }

        } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            // bad auth
            error = true;
            errorResult = "Unauthorized";
        } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
            error = true;
            InputStream response;
            response = urlConnection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("error")) {
                    // error = Internal Error on bad structure_id
                    errorResult = object.getString("error");
                    log.info("errorResult=" + errorResult);
                }
            }
        } else {
            error = true;
            errorResult = Integer.toString(statusCode);
        }

    } catch (IOException e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("IOException: " + errorResult);
    } catch (Exception e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("Exception: " + errorResult);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    if (error)
        away_status = "Error: " + errorResult;
    return away_status;
}

From source file:org.sonarqube.tests.user.OAuth2IdentityProviderTest.java

private void simulateRedirectionToCallback() {
    fakeServerAuthProvider.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
            .addHeader(/*from   w ww.j  av a2s.c  o  m*/
                    "Location: " + orchestrator.getServer().getUrl() + "/oauth2/callback/" + FAKE_PROVIDER_KEY)
            .setBody("Redirect to SonarQube"));
}

From source file:com.elevenpaths.googleindexretriever.GoogleSearch.java

public String responseCaptcha(String responseCaptcha) {
    String url = "https://ipv4.google.com/sorry/CaptchaRedirect";
    String request = url + "?q=" + q + "&hl=es&continue=" + continueCaptcha + "&id=" + idCaptcha + "&captcha="
            + responseCaptcha + "&submit=Enviar";
    String newCookie = "";

    try {//  ww w  .  java2  s  .c o  m
        URL obj = new URL(request);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        // add request header
        con.setRequestProperty("Host", "ipv4.google.com");
        con.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
        con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        con.setRequestProperty("Accept-Language", "es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3");
        con.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
        con.setRequestProperty("Cookie", tokenCookie + "; path=/; domain=google.com");
        con.addRequestProperty("Connection", "keep-alive");
        con.setRequestProperty("Referer", referer);
        //con.connect();
        boolean redirect = false;
        con.setInstanceFollowRedirects(false);
        int status = con.getResponseCode();

        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        if (redirect) {

            // get redirect url from "location" header field
            String newUrl = con.getHeaderField("Location");

            // open the new connnection again
            con = (HttpURLConnection) new URL(newUrl).openConnection();
            con.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
            con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            con.setRequestProperty("Referer", referer);
            con.setRequestProperty("Accept-Encoding", "gzip, deflate");
            con.setRequestProperty("Cookie", tokenCookie);
            con.addRequestProperty("Connection", "keep-alive");

            // Find the cookie
            String nextURL = URLDecoder.decode(newUrl, "UTF-8");
            String[] k = nextURL.split("&");
            for (String a : k) {
                if (a.startsWith("google_abuse=")) {
                    String temp = a.replace("google_abuse=", "");
                    String[] c = temp.split(";");
                    for (String j : c) {
                        if (j.startsWith("GOOGLE_ABUSE_EXEMPTION")) {
                            newCookie = j;
                        }
                    }

                }
            }
        }

        con.connect();

        if (con.getResponseCode() == 200) {
            newCookie = tokenCookie;
        }
    } catch (IOException e) {
        e.printStackTrace();

    }

    return newCookie;

}

From source file:com.adaptris.http.HttpClientTransport.java

private boolean hasMoved(HttpResponse r) {
    return (r.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP)
            || (r.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM);
}

From source file:org.jboss.aerogear.unifiedpush.SenderClient.java

/**
 * checks if the given status code is a redirect (301, 302 or 303 response status code)
 *///from w  w w  .  j  av  a2s  .com
private static boolean isRedirect(int statusCode) {
    return statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP
            || statusCode == HttpURLConnection.HTTP_SEE_OTHER;
}