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:com.dopecoin.wallet.ExchangeRatesProvider.java

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

    HttpURLConnection connection = null;
    Reader reader = null;//from  w  w  w .  ja va2s  .co m

    try {
        connection = (HttpURLConnection) url.openConnection();
        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) {
                        final String rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                BigDecimal btcRate = new BigDecimal(GenericUtils.toNanoCoins(rate, 0));
                                BigInteger leafRate = btcRate.multiply(BigDecimal.valueOf(leafBtcConversion))
                                        .toBigInteger();

                                if (leafRate.signum() > 0) {
                                    rates.put(currencyCode,
                                            new ExchangeRate(currencyCode, leafRate, 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));

            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:com.avinashbehera.sabera.network.HttpClient.java

public static JSONObject SendHttpPostUsingUrlConnection(String url, JSONObject jsonObjSend) {

    URL sendUrl;/*  w  w w . j  a  v  a  2  s . c  o  m*/
    try {
        sendUrl = new URL(url);
    } catch (MalformedURLException e) {
        Log.d(TAG, "SendHttpPostUsingUrlConnection malformed URL");
        return null;
    }

    HttpURLConnection conn = null;

    try {
        conn = (HttpURLConnection) sendUrl.openConnection();
        conn.setReadTimeout(15000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setChunkedStreamingMode(1024);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.addRequestProperty("Content-length", jsonObjSend.toJSONString().length() + "");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        //writer.write(getPostDataStringfromJsonObject(jsonObjSend));
        Log.d(TAG, "jsonobjectSend = " + jsonObjSend.toString());
        //writer.write(jsonObjSend.toString());
        writer.write(String.valueOf(jsonObjSend));

        writer.flush();
        writer.close();
        os.close();

        int responseCode = conn.getResponseCode();
        Log.d(TAG, "responseCode = " + responseCode);

        if (responseCode == HttpsURLConnection.HTTP_OK) {

            Log.d(TAG, "responseCode = HTTP OK");

            InputStream instream = conn.getInputStream();

            String resultString = convertStreamToString(instream);
            instream.close();
            Log.d(TAG, "resultString = " + resultString);
            //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONParser parser = new JSONParser();
            JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");

            return jsonObjRecv;

        }

    } catch (Exception e) {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return null;

}

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

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

    HttpURLConnection connection = null;
    Reader reader = null;//from   w  ww .j  av  a2s  .co 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, Constants.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 rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                BigDecimal btcRate = new BigDecimal(GenericUtils.toNanoCoins(rate, 0));
                                BigInteger ccnRate = btcRate.multiply(BigDecimal.valueOf(ccnBtcConversion))
                                        .toBigInteger();

                                if (ccnRate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(currencyCode, ccnRate, 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 {}", 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.androidex.volley.toolbox.HurlStack.java

private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        ProgressListener progressListener = null;
        if (request instanceof ProgressListener) {
            progressListener = (ProgressListener) request;
        }//w ww .j  a va  2 s.  c  o  m
        connection.setDoOutput(true);
        connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());

        if (progressListener != null) {
            int transferredBytes = 0;
            int totalSize = body.length;
            int offset = 0;
            int chunkSize = Math.min(2048, Math.max(totalSize - offset, 0));
            while (chunkSize > 0 && offset + chunkSize <= totalSize) {
                out.write(body, offset, chunkSize);
                transferredBytes += chunkSize;
                progressListener.onProgress(transferredBytes, totalSize);
                offset += chunkSize;
                chunkSize = Math.min(chunkSize, Math.max(totalSize - offset, 0));
            }
        } else {
            out.write(body);
        }

        out.close();
    }
}

From source file:com.navercorp.volleyextensions.volleyer.multipart.stack.MultipartHurlStack.java

/**
 * <pre>// w  ww. ja  v  a 2 s .co m
 * Add a multipart and write it to output of a connection.
 *
 * NOTE : It only supports chunked transfer encoding mode,
 *        the server should supports it.
 * </pre>
 */
private static void addMultipartIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    OutputStream os = null;
    try {
        if (!(request instanceof MultipartContainer)) {
            return;
        }

        MultipartContainer container = (MultipartContainer) request;
        if (!container.hasMultipart()) {
            return;
        }

        Multipart multipart = container.getMultipart();
        if (multipart == null) {
            return;
        }

        connection.setDoOutput(true);
        connection.addRequestProperty("Content-Type", multipart.getContentType());
        // Set chunked encoding mode.
        connection.setChunkedStreamingMode(DEFAULT_CHUNK_LENGTH);
        os = connection.getOutputStream();
        multipart.write(os);
        os.flush();
    } finally {
        if (os != null) {
            os.close();
        }
    }
}

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

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

    HttpURLConnection connection = null;
    Reader reader = null;//from   w  w  w  .  j ava2  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 rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                final double btcRate = Double
                                        .parseDouble(Fiat.parseFiat(currencyCode, rate).toPlainString());
                                DecimalFormat df = new DecimalFormat("#.########");
                                df.setRoundingMode(RoundingMode.HALF_UP);
                                DecimalFormatSymbols dfs = new DecimalFormatSymbols();
                                dfs.setDecimalSeparator('.');
                                dfs.setGroupingSeparator(',');
                                df.setDecimalFormatSymbols(dfs);
                                final Fiat dogeRate = Fiat.parseFiat(currencyCode,
                                        df.format(btcRate * dogeBtcConversion));

                                if (dogeRate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(
                                            new com.dogecoin.dogecoinj.utils.ExchangeRate(dogeRate), 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;
}

From source file:org.geotools.wfs.protocol.DefaultConnectionFactory.java

private static HttpURLConnection getConnection(final URL url, final boolean tryGzip, final HttpMethod method,
        final Authenticator auth, final int timeoutMillis) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    if (POST == method) {
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);/*from www.ja  v a  2 s .  c  om*/
        /*ESRI ArcGis has a bug when sending xml and content-type = text/xml. When omitting
        it, it works fine.*/
        if (url == null || !url.toString().contains("/ArcGIS/services/")) {
            connection.setRequestProperty("Content-type", "text/xml, application/xml");
        }
    } else {
        connection.setRequestMethod("GET");
    }
    connection.setDoInput(true);
    if (tryGzip) {
        connection.addRequestProperty("Accept-Encoding", "gzip");
    }

    connection.setConnectTimeout(timeoutMillis);
    connection.setReadTimeout(timeoutMillis);

    // auth must be after connection because one branch makes the connection
    if (auth != null) {
        if (auth instanceof WFSAuthenticator) {
            WFSAuthenticator wfsAuth = (WFSAuthenticator) auth;
            String user = wfsAuth.pa.getUserName();
            char[] pass = wfsAuth.pa.getPassword();

            String combined = String.format("%s:%s", user, String.valueOf(pass));
            byte[] authBytes = combined.getBytes("US-ASCII");
            String encoded = new String(Base64.encodeBase64(authBytes));
            String authorization = "Basic " + encoded;
            connection.setRequestProperty("Authorization", authorization);
        } else {
            /*
             * FIXME this could breaks uDig. Not quite sure what to do otherwise.
             * Maybe have a mechanism that would allow an authenticator to ask the
             * datastore itself for a previously supplied user/pass.
             */
            synchronized (Authenticator.class) {
                Authenticator.setDefault(auth);
                connection.connect();
                //                Authenticator.setDefault(null);
            }
        }
    }

    return connection;
}

From source file:com.fivehundredpxdemo.android.storage.ImageFetcher.java

/**
 * Download a bitmap from a URL, write it to a disk and return the File pointer. This
 * implementation uses a simple disk cache.
 *
 * @param urlString The URL to fetch/*from  www. j  a  v a2  s .c  o m*/
 * @param maxBytes The maximum number of bytes to read before returning null to protect against
 *                 OutOfMemory exceptions.
 * @return A File pointing to the fetched bitmap
 */
public static byte[] downloadBitmapToMemory(String urlString, int maxBytes, String accessToken) {
    Log.d(TAG, "downloadBitmapToMemory - downloading - " + urlString);

    disableConnectionReuseIfNecessary();
    HttpURLConnection urlConnection = null;
    ByteArrayOutputStream out = null;
    InputStream in = null;

    try {
        final URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.addRequestProperty("Authorization", "Bearer " + accessToken);
        if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return null;
        }
        in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES);
        out = new ByteArrayOutputStream(IO_BUFFER_SIZE_BYTES);

        final byte[] buffer = new byte[128];
        int total = 0;
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            total += bytesRead;
            if (total > maxBytes) {
                return null;
            }
            out.write(buffer, 0, bytesRead);
        }
        return out.toByteArray();
    } catch (final IOException e) {
        Log.e(TAG, "Error in downloadBitmapToMemory - " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (final IOException e) {
        }
    }
    return null;
}

From source file:yandexDisk.YandexDiskAPI.java

public static String getDownloadUrl(String auth, String path) {
    if (auth == null || auth.length() == 0)
        return null;
    try {/*w ww .j  av a 2s . com*/
        URL Url = new URL(GET_DOWNLOAD_URL + URLEncoder.encode(path, "UTF-8"));
        HttpURLConnection conn = (HttpURLConnection) Url.openConnection();
        if (conn == null)
            return null;
        HttpURLConnection.setFollowRedirects(true);
        conn.setReadTimeout(20000);
        conn.setConnectTimeout(20000);
        conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        conn.addRequestProperty("Authorization", auth);
        InputStream in = getInputEncoding(conn);
        if (in == null)
            return null;
        String s = getStringFromStream(in);
        if (s == null)
            return null;
        return new JSONObject(s).getString("href");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.PAB.ibeaconreference.AppEngineSpatial.java

public static Response getOrPost(Request request) {
    mErrorMessage = null;/*from  w  w  w .  j  a  va2s. c om*/
    HttpURLConnection conn = null;
    Response response = null;
    try {
        conn = (HttpURLConnection) request.uri.openConnection();
        //            if (!mAuthenticator.authenticate(conn)) {
        //                mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage();
        //            } else 
        {
            if (request.headers != null) {
                for (String header : request.headers.keySet()) {
                    for (String value : request.headers.get(header)) {
                        conn.addRequestProperty(header, value);
                    }
                }
            }

            if (request instanceof PUT) {
                byte[] payload = ((PUT) request).body;
                String s = new String(payload, "UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);

                conn.setRequestMethod("PUT");
                JSONObject jsonobj = getJSONObject(s);
                conn.setRequestProperty("Content-Type", "application/json; charset=utf8");
                OutputStream os = conn.getOutputStream();
                os.write(jsonobj.toString().getBytes("UTF-8"));
                os.close();
            }

            if (request instanceof POST) {
                byte[] payload = ((POST) request).body;
                String s = new String(payload, "UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");

                JSONObject jsonobj = getJSONObject(s);

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

                OutputStream os = conn.getOutputStream();
                os.write(jsonobj.toString().getBytes("UTF-8"));
                os.close();

                //                    conn.setFixedLengthStreamingMode(payload.length);
                //                    conn.getOutputStream().write(payload);
                int status = conn.getResponseCode();
                if (status / 100 != 2)
                    response = new Response(status, new Hashtable<String, List<String>>(),
                            conn.getResponseMessage().getBytes());
            }

            if (response == null) {
                int a = conn.getResponseCode();
                if (a == 401) {
                    response = new Response(a, conn.getHeaderFields(), new byte[] {});
                }
                InputStream a1 = conn.getErrorStream();
                BufferedInputStream in = new BufferedInputStream(conn.getInputStream());

                byte[] body = readStream(in);

                a12 = new String(body, "US-ASCII");

                response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body);
                //   List<String> a = conn.getHeaderFields().get("aa");
            }
        }
    } catch (IOException e) {
        e.printStackTrace(System.err);

    } finally {
        if (conn != null)
            conn.disconnect();

    }
    return response;
}