Example usage for java.net HttpURLConnection addRequestProperty

List of usage examples for java.net HttpURLConnection addRequestProperty

Introduction

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

Prototype

public void addRequestProperty(String key, String value) 

Source Link

Document

Adds a general request property specified by a key-value pair.

Usage

From source file:oneDrive.OneDriveAPI.java

public static String connectWithREST(String url, String method) throws IOException, ProtocolException {
    String newURL = "";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // Connect with a REST Method: GET, DELETE, PUT
    con.setRequestMethod(method);//from w w  w .j  a  v a  2  s.  c o m
    //add request header
    con.setReadTimeout(20000);
    con.setConnectTimeout(20000);
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    if (method.equals(DELETE) || method.equals(PUT) || getSize)
        con.addRequestProperty("Authorization", "Bearer " + ACCESS_TOKEN);

    int responseCode = con.getResponseCode();
    // Read response
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    newURL = response.toString();

    return newURL;
}

From source file:com.mebigfatguy.polycasso.URLFetcher.java

/**
 * retrieve arbitrary data found at a specific url
 * - either http or file urls/*from   w ww.  j a  va 2s.c o  m*/
 * for http requests, sets the user-agent to mozilla to avoid
 * sites being cranky about a java sniffer
 * 
 * @param url the url to retrieve
 * @param proxyHost the host to use for the proxy
 * @param proxyPort the port to use for the proxy
 * @return a byte array of the content
 * 
 * @throws IOException the site fails to respond
 */
public static byte[] fetchURLData(String url, String proxyHost, int proxyPort) throws IOException {
    HttpURLConnection con = null;
    InputStream is = null;

    try {
        URL u = new URL(url);
        if (url.startsWith("file://")) {
            is = new BufferedInputStream(u.openStream());
        } else {
            Proxy proxy;
            if (proxyHost != null) {
                proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            } else {
                proxy = Proxy.NO_PROXY;
            }
            con = (HttpURLConnection) u.openConnection(proxy);
            con.addRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6");
            con.addRequestProperty("Accept-Charset", "UTF-8");
            con.addRequestProperty("Accept-Language", "en-US,en");
            con.addRequestProperty("Accept", "text/html,image/*");
            con.setDoInput(true);
            con.setDoOutput(false);
            con.connect();

            is = new BufferedInputStream(con.getInputStream());
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(is, baos);
        return baos.toByteArray();
    } finally {
        IOUtils.closeQuietly(is);
        if (con != null) {
            con.disconnect();
        }
    }
}

From source file:com.rimbit.android_wallet.ExchangeRatesProvider.java

private static String getURLResult(URL url, final String userAgent) {

    HttpURLConnection connection = null;
    Reader reader = null;/*from   www. ja  va 2 s .  com*/

    try {
        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) {

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);

            reader = new InputStreamReader(is, Constants.UTF_8);
            final StringBuilder content = new StringBuilder();

            Io.copy(reader, content);
            return content.toString();

        } else {
            log.warn("http status {} when fetching exchange rates from {}", responseCode, RIMBIT_EXPLORER_URL);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + RIMBIT_EXPLORER_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.alfresco.repo.web.scripts.tenant.TenantAdminSystemTest.java

private static String callOutWebScript(String urlString, String method, String ticket)
        throws MalformedURLException, URISyntaxException, IOException {
    URL url = new URL(urlString);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(method);//from w  w w.  j  a v a 2s .  co m

    if (ticket != null) {
        // add Base64 encoded authorization header
        // refer to: http://wiki.alfresco.com/wiki/Web_Scripts_Framework#HTTP_Basic_Authentication
        conn.addRequestProperty("Authorization", "Basic " + Base64.encodeBytes(ticket.getBytes()));
    }

    String result = null;
    InputStream is = null;
    BufferedReader br = null;

    try {
        is = conn.getInputStream();
        br = new BufferedReader(new InputStreamReader(is));

        String line = null;
        StringBuffer sb = new StringBuffer();
        while (((line = br.readLine()) != null)) {
            sb.append(line);
        }

        result = sb.toString();
    } finally {
        if (br != null) {
            br.close();
        }
        ;
        if (is != null) {
            is.close();
        }
        ;
    }

    return result;
}

From source file:com.bushstar.htmlcoin_android_wallet.ExchangeRatesProvider.java

private static String getURLResult(URL url, final String userAgent) {

    HttpURLConnection connection = null;
    Reader reader = null;/*  www  . ja  v a2  s .  c  om*/

    try {
        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) {

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);

            reader = new InputStreamReader(is, Constants.UTF_8);
            final StringBuilder content = new StringBuilder();

            Io.copy(reader, content);
            return content.toString();

        } else {
            log.warn("http status {} when fetching exchange rates from {}", responseCode, BTCE_URL);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + BTCE_URL, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

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

    return null;

}

From source file:com.matthewmitchell.nubits_android_wallet.ExchangeRatesProvider.java

private static String getURLResult(URL url, final String userAgent) {

    HttpURLConnection connection = null;
    Reader reader = null;/*from  w w  w. ja  v  a2s  .  c o  m*/

    try {
        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) {

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);

            reader = new InputStreamReader(is, Constants.UTF_8);
            final StringBuilder content = new StringBuilder();

            Io.copy(reader, content);
            return content.toString();

        } else {
            log.warn("http status {} when fetching exchange rates from {}", 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:com.example.pabrto.AppEngineClient.java

public static int delete(URL uri, Map<String, List<String>> headers) {
    //DELETE delete = new DELETE(uri, headers);
    int s = 0;//w  ww . jav  a  2  s.co m
    HttpURLConnection httpURLConnection = null;
    try {
        httpURLConnection = (HttpURLConnection) uri.openConnection();
        if (headers != null) {
            for (String header : headers.keySet()) {
                for (String value : headers.get(header)) {
                    httpURLConnection.addRequestProperty(header, value);
                }
            }
        }
        httpURLConnection.setRequestMethod("DELETE");
        //httpURLConnection.connect();
        s = httpURLConnection.getResponseCode();
        Log.d("TAG", "Response of delete: " + String.valueOf(s));

    } catch (IOException exception) {
        exception.printStackTrace();
    } finally {
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
    }
    return s;
}

From source file:ja.ohac.wallet.ExchangeRatesProvider.java

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

    HttpURLConnection connection = null;
    Reader reader = null;//w  ww .ja  v  a 2  s .  c  o  m

    try {
        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.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Charsets.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = 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) {
                        final String rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                final BigInteger rate = GenericUtils.parseCoin(rateStr, 0);

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

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

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", 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:com.android.volley.toolbox.http.HurlStack.java

private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    if (request.containsFile()) {
        setConnectionParametersForMultipartRequest(connection, request);
    } else {//from  ww  w.  j a  va2s.c  o  m
        byte[] body = request.getBody();
        if (body != null) {
            connection.setDoOutput(true);
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(body);
            out.close();
        }
    }
}

From source file:de.schildbach.wallet.ExchangeRatesProvider.java

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

    HttpURLConnection connection = null;
    Reader reader = null;//from  w w w  .ja  va2  s . c  om

    try {
        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.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Charsets.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = 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) {
                        final String rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                final Fiat rate = Fiat.parseFiat(currencyCode, rateStr);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(
                                            new org.bitcoinj.utils.ExchangeRate(rate), source));
                                    break;
                                }
                            } catch (final NumberFormatException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

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

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", 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;
}