Example usage for java.net HttpURLConnection setInstanceFollowRedirects

List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects

Introduction

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

Prototype

public void setInstanceFollowRedirects(boolean followRedirects) 

Source Link

Document

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

Usage

From source file:org.rhq.enterprise.server.plugins.yum.HttpReader.java

@Override
protected InputStream doOpen(URL url) throws IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("open " + url);
    }//from ww  w. j a v  a2s  .c  o  m

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setInstanceFollowRedirects(true);

    if (username != null) {
        String userInfo = username;
        if (password != null) {
            userInfo += ":" + password;
        }
        String basicAuth = "Basic " + Base64.encode(userInfo.getBytes("ISO-8859-1"));
        connection.setRequestProperty("Authorization", basicAuth);
    }
    return connection.getInputStream();
}

From source file:org.apache.phoenix.util.PhoenixMRJobUtil.java

public static String getJobsInformationFromRM(String rmhost, int rmport, Map<String, String> urlParams)
        throws MalformedURLException, ProtocolException, UnsupportedEncodingException, IOException {
    HttpURLConnection con = null;
    String response = null;//from w w  w. ja  v  a2  s .  co m
    String url = null;

    try {
        StringBuilder urlBuilder = new StringBuilder();

        urlBuilder.append(RM_HTTP_SCHEME + "://").append(rmhost).append(":").append(rmport)
                .append(RM_APPS_GET_ENDPOINT);

        if (urlParams != null && urlParams.size() != 0) {
            urlBuilder.append("?");
            for (String key : urlParams.keySet()) {
                urlBuilder.append(key + "=" + urlParams.get(key) + "&");
            }
            urlBuilder.delete(urlBuilder.length() - 1, urlBuilder.length());
        }

        url = urlBuilder.toString();
        LOG.info("Attempt to get running/submitted jobs information from RM URL = " + url);

        URL obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();
        con.setInstanceFollowRedirects(true);
        con.setRequestMethod("GET");

        con.setConnectTimeout(RM_CONNECT_TIMEOUT_MILLIS);
        con.setReadTimeout(RM_READ_TIMEOUT_MILLIS);

        response = getTextContent(con.getInputStream());
    } finally {
        if (con != null)
            con.disconnect();
    }

    LOG.info("Result of attempt to get running/submitted jobs from RM - URL=" + url + ",ResponseCode="
            + con.getResponseCode() + ",Response=" + response);

    return response;
}

From source file:com.cannabiscoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent,
        final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;/*  w ww . j  a v  a2 s  . co  m*/

    try {

        Double btcRate = 0.0;
        boolean cryptsyValue = true;
        Object result = getCoinValueBTC();

        if (result == null) {
            result = getCoinValueBTC_BTER();
            cryptsyValue = false;
            if (result == null)
                return null;
        }
        btcRate = (Double) result;

        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                    Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        String rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                double rateForBTC = Double.parseDouble(rateStr);

                                rateStr = String.format("%.8f", rateForBTC * btcRate).replace(",", ".");

                                final BigInteger rate = GenericUtils.toNanoCoins(rateStr, 0);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode,
                                            new ExchangeRate(currencyCode, rate, url.getHost()));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {}: {}",
                                        new Object[] { currencyCode, url, x.getMessage() });
                            }

                        }
                    }
                }
            }

            log.info("fetched exchange rates from {}, took {} ms", url, (System.currentTimeMillis() - start));

            //Add Bitcoin information
            if (rates.size() == 0) {
                int i = 0;
                i++;
            } else {
                rates.put(CoinDefinition.cryptsyMarketCurrency,
                        new ExchangeRate(CoinDefinition.cryptsyMarketCurrency,
                                GenericUtils.toNanoCoins(String.format("%.8f", btcRate).replace(",", "."), 0),
                                cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com"));
                rates.put("m" + CoinDefinition.cryptsyMarketCurrency,
                        new ExchangeRate("m" + CoinDefinition.cryptsyMarketCurrency,
                                GenericUtils.toNanoCoins(
                                        String.format("%.5f", btcRate * 1000).replace(",", "."), 0),
                                cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com"));
            }

            return rates;
        } else {
            log.warn("http status {} when fetching {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {

        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:org.csware.ee.utils.Tools.java

public static String GetDataByPost(String httpUrl, String parMap) {
    try {//from   ww w .j  a  v  a  2  s.  c  o  m
        URL url = new URL(httpUrl);// 
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("POST"); // ?
        connection.setRequestProperty("Accept", "application/json"); // ??
        connection.setRequestProperty("Content-Type", "application/json"); // ????
        connection.connect();
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8?
        out.append(parMap);
        out.flush();
        out.close();
        // ??
        int length = (int) connection.getContentLength();// ?
        InputStream is = connection.getInputStream();
        if (length != -1) {
            byte[] data = new byte[length];
            byte[] temp = new byte[1024];
            int readLen = 0;
            int destPos = 0;
            while ((readLen = is.read(temp)) > 0) {
                System.arraycopy(temp, 0, data, destPos, readLen);
                destPos += readLen;
            }
            String result = new String(data, "UTF-8"); // utf-8?
            return result;
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("aa:  " + e.getMessage());
    }
    return "error"; // ?
}

From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java

static String getUserInfo(String server_url, String access_token) {
    // android.os.Debug.waitForDebugger();

    // check if server is valid
    if (isEmpty(server_url) || isEmpty(access_token)) {
        return null;
    }/*from   w ww .  ja v  a  2  s .c om*/

    String userinfo_endpoint = getEndpointFromConfigOidc("userinfo_endpoint", server_url);
    if (isEmpty(userinfo_endpoint)) {
        Logd(TAG, "getUserInfo : could not get endpoint on server : " + server_url);
        return null;
    }

    Logd(TAG, "getUserInfo : " + userinfo_endpoint);
    // build connection
    HttpURLConnection huc = getHUC(userinfo_endpoint);
    huc.setInstanceFollowRedirects(false);
    // huc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

    huc.setRequestProperty("Authorization", "Bearer " + access_token);

    // default result
    String result = null;

    try {
        // try to establish connection 
        huc.connect();
        // get result
        int responseCode = huc.getResponseCode();
        Logd(TAG, "getUserInfo 2 response: " + responseCode);

        // if 200, read http body
        if (responseCode == 200) {
            InputStream is = huc.getInputStream();
            result = convertStreamToString(is);
            is.close();
        }

        // close connection
        huc.disconnect();

    } catch (Exception e) {
        Logd(TAG, "getUserInfo failed");
        e.printStackTrace();
    }

    return result;
}

From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java

static String getTimUserInfo(String server_url, String tim_access_token) {
    // android.os.Debug.waitForDebugger();
    // default result
    String result = null;//  w ww.j av  a  2 s  .c  o m

    // check if server is valid
    if (isEmpty(server_url) || isEmpty(tim_access_token)) {
        Logd(TAG, "getTimUserInfo no server url or tim_access_token");
        return null;
    }

    if (!server_url.endsWith("/"))
        server_url += "/";

    // get user info endpoint
    String userinfo_endpoint = getEndpointFromConfigOidc("userinfo_endpoint", server_url);
    if (isEmpty(userinfo_endpoint)) {
        Logd(TAG, "getTimUserInfo : could not get endpoint on server : " + server_url);
        return null;
    }

    // build connection
    HttpURLConnection huc = getHUC(userinfo_endpoint);
    huc.setInstanceFollowRedirects(false);
    huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    huc.setRequestProperty("Authorization", "Bearer " + tim_access_token);
    Logd("getTimUserInfo", "bearer: " + tim_access_token);

    try {
        // try to establish connection 
        huc.connect();
        // get result
        int responseCode = huc.getResponseCode();
        Logd(TAG, "getTimUserInfo 2 response: " + responseCode);

        // if 200, read http body
        if (responseCode == 200) {
            InputStream is = huc.getInputStream();
            result = convertStreamToString(is);
            is.close();
            Logd(TAG, "getTimUserInfo 2 result: " + result);
        } else {
            // result = "response code: "+responseCode;
        }

        // close connection
        huc.disconnect();

    } catch (Exception e) {
        Log.e(TAG, "getTimUserInfo FAILED");
        e.printStackTrace();
    }

    return result;
}

From source file:org.jboss.as.test.integration.management.console.WebConsoleRedirectionTestCase.java

private HttpURLConnection getConnection() throws Exception {
    final URL url = new URL("http://" + TestSuiteEnvironment.getServerAddress() + ":"
            + TestSuiteEnvironment.getServerPort() + "/");
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    assertNotNull(connection);//from ww w  . java2 s. c o m
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod(HttpGet.METHOD_NAME);
    connection.connect();
    return connection;
}

From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java

public static boolean logout(String server_url, String tim_access_token) {

    if (isEmpty(server_url)) {
        Logd(TAG, "logout failed : no server url");
        return false;
    }/*from   w w  w  .j  a v  a2 s.co  m*/

    // get revoke_logout endpoint
    String revoke_logout_endpoint = getEndpointFromConfigOidc("revoke_logout_endpoint", server_url);
    if (isEmpty(revoke_logout_endpoint)) {
        Logd(TAG, "logout : could not get revoke_logout_endpoint on server : " + server_url);
        return false;
    }

    // set up connection
    HttpURLConnection huc = getHUC(revoke_logout_endpoint);
    huc.setInstanceFollowRedirects(false);

    huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    huc.setDoOutput(true);
    huc.setChunkedStreamingMode(0);
    // prepare parameters
    List<NameValuePair> nameValuePairs = null;
    if (tim_access_token != null && tim_access_token.length() > 0) {
        nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("tat", tim_access_token));
    }

    try {
        // write parameters to http connection
        if (nameValuePairs != null) {
            OutputStream os = huc.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            // get URL encoded string from list of key value pairs
            String postParam = getQuery(nameValuePairs);
            Logd("Logout", "url: " + revoke_logout_endpoint);
            Logd("Logout", "POST: " + postParam);
            writer.write(postParam);
            writer.flush();
            writer.close();
            os.close();
        }

        // try to connect
        huc.connect();
        // connection status
        int responseCode = huc.getResponseCode();
        Logd(TAG, "Logout response: " + responseCode);
        // if 200 - OK
        if (responseCode == 200) {
            return true;
        }
        huc.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:piuk.MyRemoteWallet.java

private static String fetchURL(String URL) throws Exception {

    if (URL.indexOf("?") > 0) {
        URL += "&api_code=" + getApiCode();
    } else {/* w w w  . j  a va  2  s. c  o m*/
        URL += "?api_code=" + getApiCode();
    }

    URL url = new URL(URL);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    try {
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestMethod("GET");

        connection.setConnectTimeout(180000);
        connection.setReadTimeout(180000);

        connection.setInstanceFollowRedirects(false);

        connection.connect();

        if (connection.getResponseCode() == 200)
            return IOUtils.toString(connection.getInputStream(), "UTF-8");
        else if (connection.getResponseCode() == 500)
            throw new Exception("Error From Server: " + IOUtils.toString(connection.getErrorStream(), "UTF-8"));
        else
            throw new Exception("Unknown response from server (" + connection.getResponseCode() + ") "
                    + IOUtils.toString(connection.getErrorStream(), "UTF-8"));

    } finally {
        connection.disconnect();
    }
}

From source file:h2weibo.utils.filters.FlickrImageFilter.java

private String extraceFromShortURL(String input) {
    Pattern p = Pattern.compile("flic.kr/p/(\\w+)/?.*");
    Matcher m = p.matcher(input);
    if (m.find()) {
        input = "http://www.flickr.com/photo.gne?short=" + m.group(1);

        String imageUrl = null;//from  w  ww . ja  v a 2  s. co m
        try {
            URL url = new URL(input);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            int code = conn.getResponseCode();
            if (code == 302) {
                String loc = conn.getHeaderField("location");
                imageUrl = extraceFromFullURL("http://www.flickr.com" + loc);
            }
            conn.disconnect();
        } catch (Exception e) {
            log.error("Not able to handle flickr's short url/", e);
        }
        return imageUrl;
    } else {
        return null;
    }
}