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:uk.ac.ucl.excites.sapelli.collector.util.AsyncDownloader.java

private boolean download(String downloadUrl) {
    if (downloadUrl == null || downloadUrl.isEmpty()) {
        failure = new Exception("No URL given!");
        return false;
    }/* w w w  .  ja v a2s  .  c om*/

    //Log.d(getClass().getSimpleName(), "Download URL: " + downloadUrl);
    if (DeviceControl.isOnline(context)) {
        InputStream input = null;
        OutputStream output = null;
        try {
            URL url = new URL(downloadUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setInstanceFollowRedirects(false); // we handle redirects manually below (otherwise HTTP->HTTPS redirects don't work):
            conn.connect();

            // Detect & follow redirects:
            int status = conn.getResponseCode();
            //Log.d(getClass().getSimpleName(), "Response Code: " + status);
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER) { // follow redirect url from "location" header field
                String newUrl = conn.getHeaderField("Location");
                //Log.d(getClass().getSimpleName(), "Redirect to URL : " + newUrl);
                return download(newUrl);
            }

            // Getting file length
            final int fileLength = conn.getContentLength();
            publishProgress(fileLength < 0 ? // when fileLength = -1 this means the server hasn't specified the file length
                    -1 : // progressDialog will open and be set to indeterminate mode
                    0); // progressDialog will open and be set to 0

            // Input stream to read file - with 8k buffer
            input = new BufferedInputStream(url.openStream(), 8192);
            // Output stream to write file
            output = new BufferedOutputStream(new FileOutputStream(downloadedFile));

            byte data[] = new byte[1024];
            int total = 0;
            int percentage = 0;
            int bytesRead;
            while ((bytesRead = input.read(data)) != -1) {
                // Complete % completion:
                if (fileLength > 0) // don't divide by 0 and only update progress if we know the fileLength (i.e. != -1)
                {
                    int newPercentage = (int) ((total += bytesRead) / ((float) fileLength) * 100f);
                    if (newPercentage != percentage)
                        publishProgress(percentage = newPercentage);
                }

                // Write data to file...
                output.write(data, 0, bytesRead);
            }

            // Flush output:
            output.flush();
        } catch (Exception e) {
            failure = e;
            return false;
        } finally { // Close streams:
            StreamHelpers.SilentClose(input);
            StreamHelpers.SilentClose(output);
        }
        //Log.d(getClass().getSimpleName(), "Download done");
        return true;
    } else {
        failure = new Exception("The device is not online.");
        return false;
    }
}

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

public static void executeLogout(HttpClient httpConn, URL warURL) throws IOException {
    HttpGet logout = new HttpGet(warURL + "Logout");
    logout.setParams(new BasicHttpParams().setParameter("http.protocol.handle-redirects", false));
    HttpResponse response = httpConn.execute(logout);

    int statusCode = response.getStatusLine().getStatusCode();
    assertTrue("Logout: Didn't saw HTTP_MOVED_TEMP(" + statusCode + ")",
            statusCode == HttpURLConnection.HTTP_MOVED_TEMP);

    Header location = response.getFirstHeader("Location");
    assertTrue("Get of " + warURL + "Logout not redirected to login page",
            location.getValue().indexOf("index.html") >= 0);
}

From source file:org.fao.geonet.utils.GeonetHttpRequestFactoryTest.java

@Test
public void testFollowsRedirects() throws Exception {
    final int port = 29484;
    InetSocketAddress address = new InetSocketAddress(port);
    HttpServer httpServer = HttpServer.create(address, 0);

    final Element expectedResponse = new Element("resource").addContent(new Element("id").setText("test"));
    HttpHandler finalHandler = new HttpHandler() {

        @Override/*  w ww.  ja v a  2 s .c  om*/
        public void handle(HttpExchange exchange) throws IOException {
            byte[] response = Xml.getString(expectedResponse).getBytes();
            exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
            exchange.getResponseBody().write(response);
            exchange.close();
        }
    };
    final String finalUrlPath = "/final.xml";
    httpServer.createContext(finalUrlPath, finalHandler);

    HttpHandler permRedirectHandler = new HttpHandler() {

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            byte[] response = finalUrlPath.getBytes();
            exchange.getResponseHeaders().add("location", finalUrlPath);
            exchange.sendResponseHeaders(HttpURLConnection.HTTP_MOVED_PERM, response.length);
            exchange.getResponseBody().write(response);
            exchange.close();
        }
    };
    final String permUrlPath = "/permRedirect.xml";
    httpServer.createContext(permUrlPath, permRedirectHandler);

    HttpHandler tempRedirectHandler = new HttpHandler() {

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            byte[] response = finalUrlPath.getBytes();
            exchange.getResponseHeaders().add("location", finalUrlPath);
            exchange.sendResponseHeaders(HttpURLConnection.HTTP_MOVED_TEMP, response.length);
            exchange.getResponseBody().write(response);
            exchange.close();
        }
    };
    final String tempUrlPath = "/tempRedirect.xml";
    httpServer.createContext(tempUrlPath, tempRedirectHandler);

    try {
        httpServer.start();
        XmlRequest xmlRequest = new GeonetHttpRequestFactory()
                .createXmlRequest(new URL("http://localhost:" + port + permUrlPath));
        Element response = xmlRequest.execute();
        assertEquals(Xml.getString(expectedResponse), Xml.getString(response));

        xmlRequest = new GeonetHttpRequestFactory()
                .createXmlRequest(new URL("http://localhost:" + port + tempUrlPath));
        response = xmlRequest.execute();
        assertEquals(Xml.getString(expectedResponse), Xml.getString(response));
    } finally {
        httpServer.stop(0);
    }
}

From source file:io.github.hidroh.materialistic.accounts.UserServicesClient.java

@Override
public void submit(Context context, String title, String content, boolean isUrl, Callback callback) {
    Pair<String, String> credentials = AppUtils.getCredentials(context);
    if (credentials == null) {
        callback.onDone(false);/* w w  w  .  j  a v  a2 s .c o  m*/
        return;
    }
    /**
     * The flow:
     * POST /submit with acc, pw
     *  if 302 to /login, considered failed
     * POST /r with fnid, fnop, title, url or text
     *  if 302 to /newest, considered successful
     *  if 302 to /x, considered error, maybe duplicate or invalid input
     *  if 200 or anything else, considered error
     */
    // fetch submit page with given credentials
    execute(postSubmitForm(credentials.first, credentials.second)).flatMap(
            response -> response.code() != HttpURLConnection.HTTP_MOVED_TEMP ? Observable.just(response)
                    : Observable.error(new IOException()))
            .flatMap(response -> {
                try {
                    return Observable.just(
                            new String[] { response.header(HEADER_SET_COOKIE), response.body().string() });
                } catch (IOException e) {
                    return Observable.error(e);
                } finally {
                    response.close();
                }
            }).map(array -> {
                array[1] = getInputValue(array[1], SUBMIT_PARAM_FNID);
                return array;
            })
            .flatMap(array -> !TextUtils.isEmpty(array[1]) ? Observable.just(array)
                    : Observable.error(new IOException()))
            .flatMap(array -> execute(postSubmit(title, content, isUrl, array[0], array[1])))
            .flatMap(response -> response.code() == HttpURLConnection.HTTP_MOVED_TEMP
                    ? Observable.just(Uri.parse(response.header(HEADER_LOCATION)))
                    : Observable.error(new IOException()))
            .flatMap(uri -> TextUtils.equals(uri.getPath(), DEFAULT_SUBMIT_REDIRECT) ? Observable.just(true)
                    : Observable.error(buildException(uri)))
            .observeOn(AndroidSchedulers.mainThread()).subscribe(callback::onDone, callback::onError);
}

From source file:cc.arduino.utils.network.FileDownloader.java

private void downloadFile(boolean noResume) throws InterruptedException {
    RandomAccessFile file = null;

    try {/*from  w  w  w .  j a  v  a2 s  .  c  om*/
        // Open file and seek to the end of it
        file = new RandomAccessFile(outputFile, "rw");
        initialSize = file.length();

        if (noResume && initialSize > 0) {
            // delete file and restart downloading
            Files.delete(outputFile.toPath());
            initialSize = 0;
        }

        file.seek(initialSize);

        setStatus(Status.CONNECTING);

        Proxy proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(downloadUrl.toURI());
        if ("true".equals(System.getProperty("DEBUG"))) {
            System.err.println("Using proxy " + proxy);
        }

        HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection(proxy);
        connection.setRequestProperty("User-agent", userAgent);
        if (downloadUrl.getUserInfo() != null) {
            String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes()));
            connection.setRequestProperty("Authorization", auth);
        }

        connection.setRequestProperty("Range", "bytes=" + initialSize + "-");
        connection.setConnectTimeout(5000);
        setDownloaded(0);

        // Connect
        connection.connect();
        int resp = connection.getResponseCode();

        if (resp == HttpURLConnection.HTTP_MOVED_PERM || resp == HttpURLConnection.HTTP_MOVED_TEMP) {
            URL newUrl = new URL(connection.getHeaderField("Location"));

            proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(newUrl.toURI());

            // open the new connnection again
            connection = (HttpURLConnection) newUrl.openConnection(proxy);
            connection.setRequestProperty("User-agent", userAgent);
            if (downloadUrl.getUserInfo() != null) {
                String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes()));
                connection.setRequestProperty("Authorization", auth);
            }

            connection.setRequestProperty("Range", "bytes=" + initialSize + "-");
            connection.setConnectTimeout(5000);

            connection.connect();
            resp = connection.getResponseCode();
        }

        if (resp < 200 || resp >= 300) {
            throw new IOException("Received invalid http status code from server: " + resp);
        }

        // Check for valid content length.
        long len = connection.getContentLength();
        if (len >= 0) {
            setDownloadSize(len);
        }
        setStatus(Status.DOWNLOADING);

        synchronized (this) {
            stream = connection.getInputStream();
        }
        byte buffer[] = new byte[10240];
        while (status == Status.DOWNLOADING) {
            int read = stream.read(buffer);
            if (read == -1)
                break;

            file.write(buffer, 0, read);
            setDownloaded(getDownloaded() + read);

            if (Thread.interrupted()) {
                file.close();
                throw new InterruptedException();
            }
        }

        if (getDownloadSize() != null) {
            if (getDownloaded() < getDownloadSize())
                throw new Exception("Incomplete download");
        }
        setStatus(Status.COMPLETE);
    } catch (InterruptedException e) {
        setStatus(Status.CANCELLED);
        // lets InterruptedException go up to the caller
        throw e;

    } catch (SocketTimeoutException e) {
        setStatus(Status.CONNECTION_TIMEOUT_ERROR);
        setError(e);

    } catch (Exception e) {
        setStatus(Status.ERROR);
        setError(e);

    } finally {
        IOUtils.closeQuietly(file);

        synchronized (this) {
            IOUtils.closeQuietly(stream);
        }
    }
}

From source file:me.philio.ghost.ui.LoginUrlFragment.java

@Override
public void failure(RetrofitError error) {
    int status = 0;
    if (error.getResponse() != null) {
        status = error.getResponse().getStatus();
    }/*from w  ww .jav a2s . c  o  m*/
    switch (status) {
    case HttpURLConnection.HTTP_MOVED_PERM:
    case HttpURLConnection.HTTP_MOVED_TEMP:
        // Got a redirect
        Log.d(TAG, "Url is a redirect!");

        // Get the redirect url and examine to attempt to provide most
        // useful error message
        String redirectUrl = null;
        for (Header header : error.getResponse().getHeaders()) {
            if (header.getName() == null) {
                continue;
            }
            if (header.getName().equals("Location")) {
                String value = header.getValue();
                if (value.endsWith("/ghost/api/v0.1/")) {
                    redirectUrl = value.substring(0, value.length() - 16);
                } else {
                    redirectUrl = value;
                }
            }
        }
        if (redirectUrl != null) {
            mEditUrl.setError(getString(R.string.error_redirect_url_to, redirectUrl));
        } else {
            mEditUrl.setError(getString(R.string.error_redirect_url));
        }
        break;
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        // Got a 401 so could be a blog, check that the response is JSON
        Object body = error.getBodyAs(JsonObject.class);
        if (body != null && body instanceof JsonObject) {
            Log.d(TAG, "Url looks good!");
            mListener.onValidUrl(mBlogUrl);
        } else {
            mEditUrl.setError(getString(R.string.error_invalid_url));
        }
        break;
    default:
        mEditUrl.setError(getString(R.string.error_invalid_url));
        break;
    }
    mBtnValidate.setEnabled(true);
    ((LoginActivity) getActivity()).setToolbarProgressBarVisibility(false);
}

From source file:com.jwrapper.maven.java.JavaDownloadMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {/*ww  w .  j a v a  2  s . c om*/

        setupNonVerifingSSL();

        final String javaRemoteURL = javaRemoteURL();
        final String javaLocalURL = javaLocalURL();

        logger().info("javaRemoteURL: {}", javaRemoteURL);
        logger().info("javaLocalURL : {}", javaLocalURL);

        final File file = new File(javaLocalURL());

        if (!javaEveryTime() && file.exists()) {
            logger().info("Java artifact is present, skip download.");
            return;
        } else {
            logger().info("Java artifact is missing, make download.");
        }

        file.getParentFile().mkdirs();

        /** Oracle likes redirects. */
        HttpURLConnection connection = connection(javaRemoteURL());
        while (connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
            connection = connection(connection.getHeaderField("Location"));
            logger().info("redirect: {}", connection);
        }

        final ProgressInputStream input = new ProgressInputStream(connection.getInputStream(),
                connection.getContentLengthLong());

        final PropertyChangeListener listener = new PropertyChangeListener() {
            long current = System.currentTimeMillis();

            @Override
            public void propertyChange(final PropertyChangeEvent event) {
                if (System.currentTimeMillis() - current > 1000) {
                    current = System.currentTimeMillis();
                    logger().info("progress: {}", event.getNewValue());
                }
            }
        };

        input.addPropertyChangeListener(listener);

        final OutputStream output = new FileOutputStream(file);

        IOUtils.copy(input, output);

        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(output);

        if (file.length() < 1000 * 1000) {
            throw new IllegalStateException("Download failure.");
        }

        logger().info("Java artifact downloaded: {} bytes.", file.length());

    } catch (final Throwable e) {
        logger().error("", e);
        throw new MojoExecutionException("", e);
    }
}

From source file:org.apache.hadoop.mapred.TestJobHistoryServer.java

private String getRedirectUrl(String jobUrl) throws IOException {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(jobUrl);
    method.setFollowRedirects(false);/*from   w  w w  .j av  a 2s  . c om*/
    try {
        int status = client.executeMethod(method);
        Assert.assertEquals(status, HttpURLConnection.HTTP_MOVED_TEMP);

        LOG.info("Location: " + method.getResponseHeader("Location"));
        return method.getResponseHeader("Location").getValue();
    } finally {
        method.releaseConnection();
    }
}

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

/** Test form authentication of a secured servlet and validate that there is
 * a SecurityAssociation setting Subject. 
 * //  w  w w. ja  v a 2 s  .c om
 * @throws Exception
 */
public void testFormAuthSubject() throws Exception {
    log.info("+++ testFormAuthSubject");
    // Start by accessing the secured index.html of war1
    HttpClient httpConn = new HttpClient();
    GetMethod indexGet = new GetMethod(baseURLNoAuth + "form-auth/restricted/SecuredServlet");
    indexGet.setQueryString("validateSubject=true");
    int responseCode = httpConn.executeMethod(indexGet);
    String body = indexGet.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/restricted/login.html");
    formPost.addParameter("j_username", "jduke");
    formPost.addParameter("j_password", "theduke");
    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");
}

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

public int get(String url, String dest) throws IOException {
    log.debug("get:" + 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;//from   www.ja  va 2 s. c om
    authorize("GET", URL.toString(), "", "application/json,*/*");

    HttpGet httpGet = new HttpGet(URL.getPath());
    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) {
        entity.writeTo(new FileOutputStream(dest));
    }
    return code;
}