Example usage for java.net HttpURLConnection HTTP_SEE_OTHER

List of usage examples for java.net HttpURLConnection HTTP_SEE_OTHER

Introduction

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

Prototype

int HTTP_SEE_OTHER

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

Click Source Link

Document

HTTP Status-Code 303: See Other.

Usage

From source file:Main.java

private static String getRedrectUrl(String url) throws IOException {
    Response response = Jsoup.connect(url).followRedirects(false).execute();
    int status = response.statusCode();
    if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
            || status == HttpURLConnection.HTTP_SEE_OTHER) {
        return response.header("location");
    }//from w  ww .  j  a v  a 2 s.  c  om
    return null;
}

From source file:Main.java

public static URI unredirect(URI uri) throws IOException {
    if (!REDIRECTOR_DOMAINS.contains(uri.getHost())) {
        return uri;
    }//from  ww w .  ja v a 2 s . c  om
    URL url = uri.toURL();

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setInstanceFollowRedirects(false);
    connection.setDoInput(false);
    connection.setRequestMethod("HEAD");
    connection.setRequestProperty("User-Agent", "ZXing (Android)");
    try {
        connection.connect();
        switch (connection.getResponseCode()) {
        case HttpURLConnection.HTTP_MULT_CHOICE:
        case HttpURLConnection.HTTP_MOVED_PERM:
        case HttpURLConnection.HTTP_MOVED_TEMP:
        case HttpURLConnection.HTTP_SEE_OTHER:
        case 307: // No constant for 307 Temporary Redirect ?
            String location = connection.getHeaderField("Location");
            if (location != null) {
                try {
                    return new URI(location);
                } catch (URISyntaxException e) {
                    // nevermind
                }
            }
        }
        return uri;
    } finally {
        connection.disconnect();
    }
}

From source file:com.shopgun.android.sdk.network.impl.DefaultRedirectProtocol.java

@Override
public boolean isRedirectRequested(Request<?> request, HttpResponse response, ArrayList<URL> previouslyVisited)
        throws IOException {
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP
            || statusCode == HttpURLConnection.HTTP_SEE_OTHER) {
        request.addEvent("request-redirected-statuscode-" + statusCode);
        return true;
    }//w w w.  j av a 2 s  . co  m
    return false;
}

From source file:Main.java

/**
 * Return an {@link InputStream} from the given url or null if failed to retrieve the content
 * /*from w w  w  .j  a  va2  s .c o m*/
 * @param uri
 * @return
 */
static InputStream openRemoteInputStream(Uri uri) {
    java.net.URL finalUrl;
    try {
        finalUrl = new java.net.URL(uri.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    }

    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) finalUrl.openConnection();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    connection.setInstanceFollowRedirects(false);
    int code;
    try {
        code = connection.getResponseCode();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    // permanent redirection
    if (code == HttpURLConnection.HTTP_MOVED_PERM || code == HttpURLConnection.HTTP_MOVED_TEMP
            || code == HttpURLConnection.HTTP_SEE_OTHER) {
        String newLocation = connection.getHeaderField("Location");
        return openRemoteInputStream(Uri.parse(newLocation));
    }

    try {
        return (InputStream) finalUrl.getContent();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.fastbootmobile.encore.api.common.HttpGet.java

/**
 * Downloads the data from the provided URL.
 * @param inUrl The URL to get from/*from   w  ww .j  a v a 2s  .  c  om*/
 * @param query The query field. '?' + query will be appended automatically, and the query data
 *              MUST be encoded properly.
 * @return A byte array of the data
 */
public static byte[] getBytes(String inUrl, String query, boolean cached)
        throws IOException, RateLimitException {
    final String formattedUrl = inUrl + (query.isEmpty() ? "" : ("?" + query));

    Log.d(TAG, "Formatted URL: " + formattedUrl);

    URL url = new URL(formattedUrl);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestProperty("User-Agent", "OmniMusic/1.0-dev (http://www.omnirom.org)");
    urlConnection.setUseCaches(cached);
    urlConnection.setInstanceFollowRedirects(true);
    int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
    urlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
    try {
        final int status = urlConnection.getResponseCode();
        // MusicBrainz returns 503 Unavailable on rate limit errors. Parse the JSON anyway.
        if (status == HttpURLConnection.HTTP_OK) {
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            int contentLength = urlConnection.getContentLength();
            if (contentLength <= 0) {
                // No length? Let's allocate 100KB.
                contentLength = 100 * 1024;
            }
            ByteArrayBuffer bab = new ByteArrayBuffer(contentLength);
            BufferedInputStream bis = new BufferedInputStream(in);
            int character;

            while ((character = bis.read()) != -1) {
                bab.append(character);
            }
            return bab.toByteArray();
        } else if (status == HttpURLConnection.HTTP_NOT_FOUND) {
            // 404
            return new byte[] {};
        } else if (status == HttpURLConnection.HTTP_FORBIDDEN) {
            return new byte[] {};
        } else if (status == HttpURLConnection.HTTP_UNAVAILABLE) {
            throw new RateLimitException();
        } else if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == 307 /* HTTP/1.1 TEMPORARY REDIRECT */
                || status == HttpURLConnection.HTTP_SEE_OTHER) {
            // We've been redirected, follow the new URL
            final String followUrl = urlConnection.getHeaderField("Location");
            Log.e(TAG, "Redirected to: " + followUrl);
            return getBytes(followUrl, "", cached);
        } else {
            Log.e(TAG, "Error when fetching: " + formattedUrl + " (" + urlConnection.getResponseCode() + ")");
            return new byte[] {};
        }
    } finally {
        urlConnection.disconnect();
    }
}

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

/**
 * Make HTTP/JSON call to Nest and set away status.
 *
 * @param access_token OAuth token to allow access to Nest
 * @param structure_id ID of structure with thermostat
 * @param away_status Either "home" or "away"
 * @return Equal to "Success" if successful, otherwise it contains a hint on the error.
 *///from w  w w .jav a  2 s.c  o m
public static String tellNestAwayStatusCall(String access_token, String structure_id, String away_status) {

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

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

    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0");
        urlConnection.setRequestMethod("PUT");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setChunkedStreamingMode(0);

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

        String payload = "\"" + away_status + "\"";

        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(payload);
        wr.flush();
        log.info(payload);

        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);
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");
            urlConnection.setRequestProperty("Accept", "application/json");

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

            wr = new OutputStreamWriter(urlConnection.getOutputStream());
            wr.write(payload);
            wr.flush();

        }

        int statusCode = urlConnection.getResponseCode();

        log.info("statusCode=" + statusCode);
        if ((statusCode == HttpURLConnection.HTTP_OK)) {
            error = false;
        } 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) {
        return "Error: " + errorResult;
    } else {
        return "Success";
    }
}

From source file:com.github.hexocraftapi.updater.updater.Downloader.java

/**
 * Download the file and save it to the updater folder.
 *//*  ww  w .  j a  v  a  2 s  .c om*/
private boolean downloadFile() {
    BufferedInputStream in = null;
    FileOutputStream fout = null;
    try {
        // Init connection
        HttpURLConnection connection = (HttpURLConnection) initConnection(this.update.getDownloadUrl());

        // always check HTTP response code first
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP
                || responseCode == HttpURLConnection.HTTP_MOVED_PERM
                || responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
            String newUrl = connection.getHeaderField("Location");
            connection = (HttpURLConnection) initConnection(new URL(newUrl));
            responseCode = connection.getResponseCode();
        }

        // always check HTTP response code first
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            String fileURL = this.update.getDownloadUrl().toString();
            String disposition = connection.getHeaderField("Content-Disposition");
            String contentType = connection.getContentType();
            int fileLength = connection.getContentLength();

            // extracts file name from header field
            if (disposition != null) {
                int index = disposition.indexOf("filename=");
                if (index > 0)
                    fileName = disposition.substring(index + 10, disposition.length() - 1);
            }
            // extracts file name from URL
            else
                fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());

            // opens input stream from the HTTP connection
            in = new BufferedInputStream(connection.getInputStream());

            // opens an output stream to save into file
            fout = new FileOutputStream(new File(this.updateFolder, fileName));

            log(Level.INFO, "About to download a new update: " + this.update.getVersion().toString());
            final byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead;
            while ((bytesRead = in.read(buffer, 0, BUFFER_SIZE)) != -1)
                fout.write(buffer, 0, bytesRead);
            log(Level.INFO, "File downloaded: " + fileName);
        }
    } catch (Exception ex) {
        log(Level.WARNING, "The auto-updater tried to download a new update, but was unsuccessful.");
        return false;
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (final IOException ex) {
            log(Level.SEVERE, null);
            return false;
        }
        try {
            if (fout != null)
                fout.close();
        } catch (final IOException ex) {
            log(Level.SEVERE, null);
            return false;
        }
        return true;
    }
}

From source file:mdretrieval.FileFetcher.java

public static String[] loadStringFromURL(String destinationURL, boolean acceptRDF) throws IOException {
    String[] ret = new String[2];

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;

    String dest = destinationURL;
    URL url = new URL(dest);
    Proxy proxy = null;/*from   www  .j  a  v  a2 s . c o  m*/

    if (ServerConstants.isProxyEnabled) {
        proxy = new Proxy(Proxy.Type.HTTP,
                new InetSocketAddress(ServerConstants.hostname, ServerConstants.port));
        urlConnection = (HttpURLConnection) url.openConnection(proxy);
    } else {
        urlConnection = (HttpURLConnection) url.openConnection();
    }

    boolean redirect = false;

    int status = urlConnection.getResponseCode();
    if (Master.DEBUG_LEVEL >= Master.LOW)
        System.out.println("RESPONSE-CODE--> " + status);
    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) {
        String newUrl = urlConnection.getHeaderField("Location");
        dest = newUrl;
        urlConnection.disconnect();
        if (Master.DEBUG_LEVEL > Master.LOW)
            System.out.println("REDIRECT--> " + newUrl);
        urlConnection = openMaybeProxyConnection(proxy, newUrl);
    }

    try {
        urlConnection.setRequestMethod("GET");
        urlConnection.setRequestProperty("Accept", HTTP_RDFXML_PROP);
        urlConnection.setDoInput(true);
        //urlConnection.setDoOutput(true);            
        inputStream = urlConnection.getInputStream();
        ret[1] = urlConnection.getHeaderField("Content-Type");
    } catch (IllegalStateException e) {
        if (Master.DEBUG_LEVEL >= Master.LOW)
            System.out.println(" DEBUG: IllegalStateException");
        urlConnection.disconnect();
        HttpURLConnection conn2 = openMaybeProxyConnection(proxy, dest);
        conn2.setRequestMethod("GET");
        conn2.setRequestProperty("Accept", HTTP_RDFXML_PROP);
        conn2.setDoInput(true);
        inputStream = conn2.getInputStream();
        ret[1] = conn2.getHeaderField("Content-Type");
    }

    try {
        ret[0] = IOUtils.toString(inputStream);

        if (Master.DEBUG_LEVEL > Master.LOW) {
            System.out.println(" Content-type: " + urlConnection.getHeaderField("Content-Type"));
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
        urlConnection.disconnect();
    }

    if (Master.DEBUG_LEVEL > Master.LOW)
        System.out.println("Done reading " + destinationURL);
    return ret;

}

From source file:io.github.bonigarcia.wdm.Downloader.java

public static final synchronized void download(URL url, String version, String export, List<String> driverName)
        throws IOException {
    File targetFile = new File(getTarget(version, url));
    File binary = null;/*from  w  w  w  .ja v  a  2  s .co m*/

    // Check if binary exists
    boolean download = !targetFile.getParentFile().exists()
            || (targetFile.getParentFile().exists() && targetFile.getParentFile().list().length == 0)
            || WdmConfig.getBoolean("wdm.override");

    if (!download) {
        // Check if existing binary is valid
        Collection<File> listFiles = FileUtils.listFiles(targetFile.getParentFile(), null, true);
        for (File file : listFiles) {
            for (String s : driverName) {
                if (file.getName().startsWith(s) && file.canExecute()) {
                    binary = file;
                    log.debug("Using binary driver previously downloaded {}", binary);
                    download = false;
                    break;
                } else {
                    download = true;
                }
            }
            if (!download) {
                break;
            }
        }
    }

    if (download) {
        log.info("Downloading {} to {}", url, targetFile);
        HttpURLConnection conn = getConnection(url);
        int responseCode = conn.getResponseCode();
        log.debug("Response HTTP {}", responseCode);
        if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP
                || responseCode == HttpURLConnection.HTTP_MOVED_PERM
                || responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
            // HTTP Redirect
            URL newUrl = new URL(conn.getHeaderField("Location"));
            log.debug("Redirect to {}", newUrl);
            conn = getConnection(newUrl);
        }

        FileUtils.copyInputStreamToFile(conn.getInputStream(), targetFile);

        if (!export.contains("edge")) {
            binary = extract(targetFile, export);
            targetFile.delete();
        } else {
            binary = targetFile;
        }

    }
    if (export != null) {
        BrowserManager.exportDriver(export, binary.toString());
    }

}

From source file:org.niord.proxy.rest.AbstractNiordService.java

/**
 * Creates a HTTP connection to the given URL and handles redirects.
 * @param url the URL/*  w ww.  j av  a 2  s .co  m*/
 * @return a HTTP connection to the given URL and handles redirects.
 */
HttpURLConnection createHttpUrlConnection(String url) throws IOException {

    HttpURLConnection con = newHttpUrlConnection(url);

    int status = con.getResponseCode();
    if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
            || status == HttpURLConnection.HTTP_SEE_OTHER) {

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

        // open the new connection again
        con = newHttpUrlConnection(redirectUrl);
    }

    return con;
}