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:com.ratebeer.android.api.command.PostRatingCommand.java

@Override
public CommandResult execute(ApiConnection apiConnection) {
    try {// ww w  .  j  a  va2 s .c o m

        ApiConnection.ensureLogin(apiConnection, getUserSettings());
        // NOTE: Maybe use the API call to http://www.ratebeer.com/m/m_saverating.asp, but it should be checked
        // whether this allows updating of a rating too
        // NOTE: We get an HTTP 302 (moved temporarily) response if everything is okay (to redirect us)
        String result = apiConnection.post(
                ratingID <= 0 ? "http://www.ratebeer.com/saverating.asp"
                        : "http://www.ratebeer.com/updaterating.asp",
                Arrays.asList(new BasicNameValuePair("BeerID", Integer.toString(beerId)),
                        new BasicNameValuePair("RatingID", ratingID <= 0 ? "" : Integer.toString(ratingID)),
                        new BasicNameValuePair("OrigDate", origDate == null ? "" : origDate),
                        new BasicNameValuePair("aroma", Integer.toString(aroma)),
                        new BasicNameValuePair("appearance", Integer.toString(appearance)),
                        new BasicNameValuePair("flavor", Integer.toString(taste)),
                        new BasicNameValuePair("palate", Integer.toString(palate)),
                        new BasicNameValuePair("overall", Integer.toString(overall)),
                        new BasicNameValuePair("totalscore", Float.toString(getTotal())),
                        new BasicNameValuePair("Comments", comment)),
                HttpURLConnection.HTTP_MOVED_TEMP);
        if (result.indexOf(POST_SUCCESS) >= 0) {
            return new CommandSuccessResult(this);
        } else {
            return new CommandFailureResult(this, new ApiException(ApiException.ExceptionType.CommandFailed,
                    "The rating was posted, but the returned HTML did not contain the unique success string."));
        }

    } catch (ApiException e) {
        return new CommandFailureResult(this, e);
    }
}

From source file:com.sonar.it.jenkins.orchestrator.container.JenkinsDownloader.java

private File downloadUrl(String url, File toFile) {
    try {//www .  ja  va 2 s.  co  m
        FileUtils.forceMkdir(toFile.getParentFile());

        HttpURLConnection conn;
        URL u = new URL(url);

        LOG.info("Download: " + u);
        // gets redirected multiple times, including from https -> http, so not done by Java

        while (true) {
            conn = (HttpURLConnection) u.openConnection();
            conn.connect();
            if (conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM
                    || conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
                String newLocationHeader = conn.getHeaderField("Location");
                LOG.info("Redirect: " + newLocationHeader);
                conn.disconnect();
                u = new URL(newLocationHeader);
                continue;
            }
            break;
        }

        InputStream is = conn.getInputStream();
        ByteStreams.copy(is, Files.asByteSink(toFile).openBufferedStream());
        LOG.info("Downloaded to: " + toFile);
        return toFile;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

}

From source file:org.apache.maven.wagon.providers.http.LightweightHttpWagon.java

public void fillInputData(InputData inputData)
        throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    Resource resource = inputData.getResource();

    String visitingUrl = buildUrl(resource.getName());
    try {/*  w  w  w . ja  v a2s. c om*/
        List<String> visitedUrls = new ArrayList<String>();

        for (int redirectCount = 0; redirectCount < MAX_REDIRECTS; redirectCount++) {
            if (visitedUrls.contains(visitingUrl)) {
                throw new TransferFailedException("Cyclic http redirect detected. Aborting! " + visitingUrl);
            }
            visitedUrls.add(visitingUrl);

            URL url = new URL(visitingUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(this.proxy);

            urlConnection.setRequestProperty("Accept-Encoding", "gzip");
            if (!useCache) {
                urlConnection.setRequestProperty("Pragma", "no-cache");
            }

            addHeaders(urlConnection);

            // TODO: handle all response codes
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_FORBIDDEN
                    || responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new AuthorizationException("Access denied to: " + buildUrl(resource.getName()));
            }
            if (responseCode == HttpURLConnection.HTTP_MOVED_PERM
                    || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                visitingUrl = urlConnection.getHeaderField("Location");
                continue;
            }

            InputStream is = urlConnection.getInputStream();
            String contentEncoding = urlConnection.getHeaderField("Content-Encoding");
            boolean isGZipped = contentEncoding != null && "gzip".equalsIgnoreCase(contentEncoding);
            if (isGZipped) {
                is = new GZIPInputStream(is);
            }
            inputData.setInputStream(is);
            resource.setLastModified(urlConnection.getLastModified());
            resource.setContentLength(urlConnection.getContentLength());
            break;
        }
    } catch (MalformedURLException e) {
        throw new ResourceDoesNotExistException("Invalid repository URL: " + e.getMessage(), e);
    } catch (FileNotFoundException e) {
        throw new ResourceDoesNotExistException("Unable to locate resource in repository", e);
    } catch (IOException e) {
        StringBuilder message = new StringBuilder("Error transferring file: ");
        message.append(e.getMessage());
        message.append(" from " + visitingUrl);
        if (getProxyInfo() != null && getProxyInfo().getHost() != null) {
            message.append(" with proxyInfo ").append(getProxyInfo().toString());
        }
        throw new TransferFailedException(message.toString(), e);
    }
}

From source file:org.jboss.test.security.test.SecurityDomainTolerateUnitTestCase.java

public void testWeb() throws Exception {
    String baseURLNoAuth = "http://" + getServerHost() + ":" + Integer.getInteger("web.port", 8080) + "/";
    HttpClient httpConn = new HttpClient();
    GetMethod indexGet = new GetMethod(baseURLNoAuth + "sdtolerate/");
    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;/*from w w  w.j  a  v  a 2s.  co  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 + "sdtolerate/j_security_check");
    formPost.addRequestHeader("Referer", baseURLNoAuth + "sdtolerate/login.jsp");
    formPost.addParameter("j_username", this.username);
    formPost.addParameter("j_password", new String(password));
    responseCode = httpConn.executeMethod(formPost);
    String loginResult = formPost.getResponseBodyAsString();
    if (loginResult.indexOf("Encountered a login error") > 0)
        fail("Login Failed");

    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 index.jsp
    Header location = formPost.getResponseHeader("Location");
    String indexURI = location.getValue();
    GetMethod war1Index = new GetMethod(indexURI);
    responseCode = httpConn.executeMethod(war1Index);
    response = war1Index.getStatusText();
    log.debug("responseCode=" + responseCode + ", response=" + response);
    assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
}

From source file:org.jboss.test.security.test.CustomPrincipalPropagationUnitTestCase.java

/**
 * A web-app has a welcome jsp (called as index.jsp). Inside this jsp,
 * there is a call made out to an ejb//from   w  ww.j  a v a 2 s  . co  m
 * 
 * @throws Exception
 */
public void testCustomPrincipalTransmissionInVM() throws Exception {
    String baseURLNoAuth = "http://" + getServerHost() + ":" + Integer.getInteger("web.port", 8080) + "/";
    HttpClient httpConn = new HttpClient();
    GetMethod indexGet = new GetMethod(baseURLNoAuth + "custom-principal/");
    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;
    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 + "custom-principal/j_security_check");
    formPost.addRequestHeader("Referer", baseURLNoAuth + "custom-principal/login.jsp");
    formPost.addParameter("j_username", this.username);
    formPost.addParameter("j_password", new String(password));
    responseCode = httpConn.executeMethod(formPost.getHostConfiguration(), formPost, state);
    String loginResult = formPost.getResponseBodyAsString();
    if (loginResult.indexOf("Encountered a login error") > 0)
        fail("Login Failed");

    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 index.jsp
    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();
    log.debug("Final result obtained:" + body);
    if (body.indexOf("j_security_check") > 0)
        fail("get of " + indexURI + " redirected to login page");
    if (body.indexOf("Propagation Success") < 0)
        fail("Propagation of custom principal within VM failed");
}

From source file:fr.seeks.SuggestionProvider.java

public void setCursorOfQueryThrow(Uri uri, String query, MatrixCursor matrix)
        throws MalformedURLException, IOException {
    String url = getUrlFromKeywords(query);
    Log.v(TAG, "Query:" + url);

    String json = null;//from  w w w  .j a v  a 2  s . c o m

    while (json == null) {
        HttpURLConnection connection = null;
        connection = (HttpURLConnection) (new URL(url)).openConnection();

        try {
            connection.setDoOutput(true);
            connection.setChunkedStreamingMode(0);
            connection.setInstanceFollowRedirects(true);

            connection.connect();
            int response = connection.getResponseCode();
            if (response == HttpURLConnection.HTTP_MOVED_PERM
                    || response == HttpURLConnection.HTTP_MOVED_TEMP) {
                Map<String, List<String>> list = connection.getHeaderFields();
                for (Entry<String, List<String>> entry : list.entrySet()) {
                    String value = "";
                    for (String s : entry.getValue()) {
                        value = value + ";" + s;
                    }
                    Log.v(TAG, entry.getKey() + ":" + value);
                }
                // FIXME
                url = "";
                return;
            }
            InputStream in = connection.getInputStream();

            BufferedReader r = new BufferedReader(new InputStreamReader(in));
            StringBuilder builder = new StringBuilder();

            String line;
            while ((line = r.readLine()) != null) {
                builder.append(line);
            }

            json = builder.toString();

            /*
             * Log.v(TAG, "** JSON START **"); Log.v(TAG, json); Log.v(TAG,
             * "** JSON END **");
             */
        } catch (IOException e) {
            e.printStackTrace();
            return;
        } finally {
            connection.disconnect();
        }
    }

    JSONArray snippets;
    JSONObject object;
    JSONArray suggestions;

    Boolean show_snippets = mPrefs.getBoolean("show_snippets", false);
    if (show_snippets) {
        try {
            object = (JSONObject) new JSONTokener(json).nextValue();
            snippets = object.getJSONArray("snippets");
        } catch (JSONException e) {
            e.printStackTrace();
            return;
        }
        Log.v(TAG, "Snippets found: " + snippets.length());
        for (int i = 0; i < snippets.length(); i++) {
            JSONObject snip;
            try {
                snip = snippets.getJSONObject(i);
                matrix.newRow().add(i).add(snip.getString("title")).add(snip.getString("summary"))
                        .add(snip.getString("title")).add(Intent.ACTION_SEND).add(snip.getString("url"));
            } catch (JSONException e) {
                e.printStackTrace();
                continue;
            }
        }
    } else {
        try {
            object = (JSONObject) new JSONTokener(json).nextValue();
            suggestions = object.getJSONArray("suggestions");
        } catch (JSONException e) {
            e.printStackTrace();
            return;
        }
        Log.v(TAG, "Suggestions found: " + suggestions.length());
        for (int i = 0; i < suggestions.length(); i++) {
            try {
                matrix.newRow().add(i).add(suggestions.getString(i)).add("").add(suggestions.getString(i))
                        .add(Intent.ACTION_SEARCH).add("");
            } catch (JSONException e) {
                e.printStackTrace();
                continue;
            }
        }
    }
    getContext().getContentResolver().notifyChange(uri, null);

}

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

private String doSsoLogin(final HttpContext httpContext, final HttpPost postForm) throws IOException {
    HttpResponse response;//from   www  . ja  v  a  2  s  .c om
    log.debug("Login via posting form-data to " + postForm.getURI());
    try {
        response = httpClient.execute(postForm, httpContext);
        if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_MOVED_TEMP) {
            throw getSsoExceptionFromFormResults(httpContext, response);
        }
        return response.getFirstHeader("Location").getValue();
    } finally {
        postForm.releaseConnection();
    }
}

From source file:org.jboss.test.web.security.GenericHeaderAuthUnitTestCase.java

/**
 * <p>//from  w ww. j av  a2s. co  m
 * Check that, in the absence of headers, regular form authentication takes place.
 * </p>
 * 
 * @throws Exception if an error occurs when running the test.
 */
public void testRegularFormAuth() throws Exception {
    GetMethod getMethod = new GetMethod(this.testAppBaseURL + this.securedServletPath);
    // execute a plain request to the SecureServlet
    try {
        int responseCode = this.httpClient.executeMethod(getMethod);
        String body = getMethod.getResponseBodyAsString();
        // check the response code and assert the redirection to the login page
        assertTrue("Unexpected response code received: " + responseCode,
                responseCode == HttpURLConnection.HTTP_OK);
        assertTrue("Failed to redirect the request to the login page", body.indexOf("j_security_check") > 0);
    } finally {
        getMethod.releaseConnection();
    }

    HttpState state = this.httpClient.getState();
    // fill in the login form and submit it
    PostMethod postMethod = new PostMethod(this.testAppBaseURL + "j_security_check");
    postMethod.addRequestHeader("Referer", this.testAppBaseURL + "restricted/login.html");
    postMethod.addParameter("j_username", "jduke");
    postMethod.addParameter("j_password", "theduke");
    Header location = null;
    try {
        int responseCode = this.httpClient.executeMethod(postMethod.getHostConfiguration(), postMethod, state);
        log.debug("responseCode=" + responseCode + ", response=" + postMethod.getStatusText());
        // check the response code received and the presence of a location header in the response
        assertTrue("Unexpected response code received: " + responseCode,
                responseCode == HttpURLConnection.HTTP_MOVED_TEMP);
        location = postMethod.getResponseHeader("Location");
        assertNotNull("Location header not found in response", location);
    } finally {
        postMethod.releaseConnection();
    }

    // follow the redirect as defined by the location header
    String indexURI = location.getValue();
    getMethod = new GetMethod(indexURI);
    try {
        int responseCode = this.httpClient.executeMethod(getMethod.getHostConfiguration(), getMethod, state);
        log.debug("responseCode=" + responseCode + ", response=" + getMethod.getStatusText());
        // check the reponse code received
        assertTrue("Unexpected response code received: " + responseCode,
                responseCode == HttpURLConnection.HTTP_OK);
        String body = getMethod.getResponseBodyAsString();
        // assert the redirection of to the SecureServlet
        assertTrue("Redirect to SecureServlet has failed", body.indexOf("SecureServlet") > 0);
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:org.jboss.test.web.security.CustomHeaderAuthTestCase.java

private 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;//from   w  w w . ja  v  a2s.c  om
    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 + "header-form-auth/j_security_check");
    formPost.addRequestHeader("Referer", baseURLNoAuth + "header-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:org.sociotech.communitymashup.source.mendeley.sdkadaption.AdaptedDocumentServiceImpl.java

protected String callGetForRedirectUrl(String apiUrl) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);

    try {//ww w.ja  v a  2 s  . c  o  m
        HttpGet httpget = new HttpGet(apiUrl);
        if (!requestParameters.isEmpty()) {
            HttpParams params = httpget.getParams();
            for (String name : requestParameters.keySet()) {
                params.setParameter(name, requestParameters.get(name));
            }
        }

        for (String headerName : requestHeaders.keySet()) {
            httpget.addHeader(headerName, requestHeaders.get(headerName));
        }

        signRequest(httpget);

        HttpResponse response = httpclient.execute(httpget);

        if (!((response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_MOVED_TEMP)
                || (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_MOVED_PERM)
                || (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_SEE_OTHER))) {
            return null;
        }

        // redirect location is in location header
        Header[] locationHeader = response.getHeaders("location");

        if (locationHeader.length >= 1) {
            return locationHeader[0].getValue();
        }
    } catch (IOException e) {
        throw new MendeleyException(e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        // httpclient.getConnectionManager().shutdown();
    }

    return null;
}