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.AddToCellarCommand.java

@Override
protected void makeRequest(ApiConnection apiConnection) throws ApiException {
    ApiConnection.ensureLogin(apiConnection, getUserSettings());
    if (isWant()) {
        apiConnection.post("http://www.ratebeer.com/beerlistwant-process.asp",
                Arrays.asList(new BasicNameValuePair("BeerID", Integer.toString(beerId)),
                        new BasicNameValuePair("memo", memo), new BasicNameValuePair("submit", "Add")),
                HttpURLConnection.HTTP_MOVED_TEMP);
    } else {//from   w ww  . j a  va 2s. c o m
        apiConnection.post("http://www.ratebeer.com/beerlisthave-process.asp",
                Arrays.asList(new BasicNameValuePair("BeerID", Integer.toString(beerId)),
                        new BasicNameValuePair("Update", "0"), new BasicNameValuePair("vintage", vintage),
                        new BasicNameValuePair("memo", memo), new BasicNameValuePair("quantity", quantity),
                        new BasicNameValuePair("submit", "Add")),
                HttpURLConnection.HTTP_MOVED_TEMP);
    }
}

From source file:uk.co.jassoft.network.Network.java

public InputStream read(String httpUrl, String method, boolean cache) throws IOException {

    HttpURLConnection conn = null;
    try {//w  ww .  java  2  s .  co  m

        URL base, next;
        String location;

        while (true) {
            // inputing the keywords to google search engine
            URL url = new URL(httpUrl);

            //                if(cache) {
            //                    //Proxy instance, proxy ip = 10.0.0.1 with port 8080
            //                    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("cache", 3128));
            //                    // makking connection to the internet
            //                    conn = (HttpURLConnection) url.openConnection(proxy);
            //                }
            //                else {
            conn = (HttpURLConnection) url.openConnection();
            //                }

            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
            conn.setRequestMethod(method);
            conn.setRequestProperty("User-Agent",
                    "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 ( .NET CLR 3.5.30729)");
            conn.setRequestProperty("Accept-Encoding", "gzip");

            switch (conn.getResponseCode()) {
            case HttpURLConnection.HTTP_MOVED_PERM:
            case HttpURLConnection.HTTP_MOVED_TEMP:
                location = conn.getHeaderField("Location");
                base = new URL(httpUrl);
                next = new URL(base, location); // Deal with relative URLs
                httpUrl = next.toExternalForm();
                continue;
            }

            break;
        }

        if (!conn.getContentType().startsWith("text/") || conn.getContentType().equals("text/xml")) {
            throw new IOException(String.format("Content of story is not Text. Returned content type is [%s]",
                    conn.getContentType()));
        }

        if ("gzip".equals(conn.getContentEncoding())) {
            return new GZIPInputStream(conn.getInputStream());
        }

        // getting the input stream of page html into bufferedreader
        return conn.getInputStream();
    } catch (Exception exception) {
        throw new IOException(exception);
    } finally {
        if (conn != null && conn.getErrorStream() != null) {
            conn.getErrorStream().close();
        }
    }
}

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

/**
 * Downloads the data from the provided URL.
 * @param inUrl The URL to get from/*  ww w. j  av  a  2  s  .  c o  m*/
 * @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 .j  a  v 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:org.jboss.test.web.test.SSOBaseCase.java

public static void executeLogout(HttpClient httpConn, String warURL) throws IOException, HttpException {
    GetMethod logout = new GetMethod(warURL + "Logout");
    logout.setFollowRedirects(false);/*  w  w w. ja va 2 s .  c o m*/
    int responseCode = httpConn.executeMethod(logout.getHostConfiguration(), logout, httpConn.getState());
    assertTrue("Logout: Saw HTTP_MOVED_TEMP(" + responseCode + ")",
            responseCode == HttpURLConnection.HTTP_MOVED_TEMP);
    Header location = logout.getResponseHeader("Location");
    String indexURI = location.getValue();
    if (indexURI.indexOf("index.html") < 0)
        fail("get of " + warURL + "Logout not redirected to login page");
}

From source file:com.astamuse.asta4d.web.dispatch.RedirectUtil.java

public static void redirectToUrlWithSavedFlashScopeData(HttpServletResponse response, int status, String url) {

    // regulate status
    if (status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_MOVED_TEMP) {
        ///*from   w  w  w. j  ava  2 s.  c  om*/
    } else {
        status = HttpURLConnection.HTTP_MOVED_TEMP;
    }

    // check illegal url
    if (url.indexOf('\n') >= 0 || url.indexOf('\r') >= 0) {
        throw new RuntimeException("illegal redirct url:" + url);
    }

    // before redirect task
    Map<String, RedirectInterceptor> interceptorMap = Context.getCurrentThreadContext()
            .getData(RedirectInterceptorMapKey);
    if (interceptorMap != null) {
        for (RedirectInterceptor interceptor : interceptorMap.values()) {
            interceptor.beforeRedirect();
        }
        addFlashScopeData(RedirectInterceptorMapKey, interceptorMap);
    }

    // create flash data map
    Map<String, Object> dataMap = new HashMap<String, Object>();
    WebApplicationContext context = Context.getCurrentThreadContext();
    List<Map<String, Object>> dataList = context.getData(FlashScopeDataListKey);
    if (dataList != null) {
        for (Map<String, Object> map : dataList) {
            dataMap.putAll(map);
        }
    }

    // save flash data map
    if (!dataMap.isEmpty()) {
        String flashScopeId = SecureIdGenerator.createEncryptedURLSafeId();
        WebApplicationConfiguration.getWebApplicationConfiguration().getExpirableDataManager().put(flashScopeId,
                dataMap, DATA_EXPIRE_TIME_MILLI_SECONDS);

        // create target url
        if (url.contains("?")) {
            url = url + '&' + KEY_FLASH_SCOPE_ID + '=' + flashScopeId;
        } else {
            url = url + '?' + KEY_FLASH_SCOPE_ID + '=' + flashScopeId;
        }
    }

    // do redirection
    response.setStatus(status);
    response.addHeader("Location", url);
}

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

/**
 * Download the file and save it to the updater folder.
 *///from   w w  w .  ja v  a2 s . co  m
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 w  w w.  ja v a 2s . com*/

    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;// www  .  ja v a  2s  .  c om

    // 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.jboss.test.security.test.mapping.RoleMappingWebTestCase.java

/**
 * Test a FORM auth simple webapp. A role of "testRole" will
 * be mapped to Authorized User via the role mapping logic
 *//* w w  w .  j  ava  2s  .  c  o m*/
public void testWebAccess() throws Exception {
    baseURLNoAuth = "http://" + getServerHost() + ":" + Integer.getInteger("web.port", 8080) + "/";
    GetMethod indexGet = new GetMethod(baseURLNoAuth + "web-role-map/Secured.jsp");
    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 + "web-role-map/j_security_check");
    formPost.addRequestHeader("Referer", baseURLNoAuth + "web-role-map/login.html");
    formPost.addParameter("j_username", "user");
    formPost.addParameter("j_password", "pass");
    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");
}