Example usage for java.net HttpURLConnection getInputStream

List of usage examples for java.net HttpURLConnection getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:flow.visibility.tapping.OpenDaylightHelper.java

/** The function for inserting the flow */

public static boolean installFlow(JSONObject postData, String user, String password, String baseURL) {

    StringBuffer result = new StringBuffer();

    /** Check the connection to ODP REST API page */

    try {//from ww w . j  a  va  2  s  .co m

        if (!baseURL.contains("http")) {
            baseURL = "http://" + baseURL;
        }
        baseURL = baseURL + "/controller/nb/v2/flowprogrammer/default/node/OF/"
                + postData.getJSONObject("node").get("id") + "/staticFlow/" + postData.get("name");

        /** Create URL = base URL + container */
        URL url = new URL(baseURL);

        /** Create authentication string and encode it to Base64*/
        String authStr = user + ":" + password;
        String encodedAuthStr = Base64.encodeBase64String(authStr.getBytes());

        /** Create Http connection */
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        /** Set connection properties */
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Authorization", "Basic " + encodedAuthStr);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        /** Set JSON Post Data */
        OutputStream os = connection.getOutputStream();
        os.write(postData.toString().getBytes());
        os.close();

        /** Get the response from connection's inputStream */
        InputStream content = (InputStream) connection.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(content));
        String line = "";
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    /** checking the result of REST API connection */

    if ("success".equalsIgnoreCase(result.toString())) {
        return true;
    } else {
        return false;
    }
}

From source file:Main.java

public static void DownloadFile(String u) {
    try {/*from   w ww.  ja  v a2  s . c  o  m*/
        Logd(TAG, "Starting download of: " + u);
        URL url = new URL(u);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.connect();
        //File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        checkStorageDir();
        File storageDir = new File(
                Environment.getExternalStorageDirectory() + "/Android/data/com.nowsci.odm/.storage");
        File file = new File(storageDir, getFileName(u));
        Logd(TAG, "Storage directory: " + storageDir.toString());
        Logd(TAG, "File name: " + file.toString());
        FileOutputStream fileOutput = new FileOutputStream(file);
        InputStream inputStream = urlConnection.getInputStream();
        byte[] buffer = new byte[1024];
        int bufferLength = 0;
        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        fileOutput.close();
        Logd(TAG, "File written");
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.denimgroup.threadfix.service.defects.RestUtils.java

public static InputStream postUrl(String urlString, String data, String username, String password) {
    URL url = null;/* w w w . j ava 2  s. c om*/
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        log.warn("URL used for POST was bad: '" + urlString + "'");
        return null;
    }

    HttpURLConnection httpConnection = null;
    OutputStreamWriter outputWriter = null;
    try {
        httpConnection = (HttpURLConnection) url.openConnection();

        setupAuthorization(httpConnection, username, password);

        httpConnection.addRequestProperty("Content-Type", "application/json");
        httpConnection.addRequestProperty("Accept", "application/json");

        httpConnection.setDoOutput(true);
        outputWriter = new OutputStreamWriter(httpConnection.getOutputStream());
        outputWriter.write(data);
        outputWriter.flush();

        InputStream is = httpConnection.getInputStream();

        return is;
    } catch (IOException e) {
        log.warn("IOException encountered trying to post to URL with message: " + e.getMessage());
        if (httpConnection == null) {
            log.warn(
                    "HTTP connection was null so we cannot do further debugging of why the HTTP request failed");
        } else {
            try {
                InputStream errorStream = httpConnection.getErrorStream();
                if (errorStream == null) {
                    log.warn("Error stream from HTTP connection was null");
                } else {
                    log.warn(
                            "Error stream from HTTP connection was not null. Attempting to get response text.");
                    String postErrorResponse = IOUtils.toString(errorStream);
                    log.warn("Error text in response was '" + postErrorResponse + "'");
                }
            } catch (IOException e2) {
                log.warn("IOException encountered trying to read the reason for the previous IOException: "
                        + e2.getMessage(), e2);
            }
        }
    } finally {
        if (outputWriter != null) {
            try {
                outputWriter.close();
            } catch (IOException e) {
                log.warn("Failed to close output stream in postUrl.", e);
            }
        }
    }

    return null;
}

From source file:com.tohours.imo.util.TohoursUtils.java

/**
 * //  www .  ja v  a2s  .c o m
 * @param path
 * @param charsetName
 * @param param
 * @return
 * @throws IOException
 */
public static String httpPost(String path, String param, String charsetName) throws IOException {
    String rv = null;
    URL url = null;
    HttpURLConnection conn = null;
    InputStream input = null;
    try {
        url = new URL(path);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "plain/text");
        conn.setRequestProperty("User-Agent", "Tohours Shake Project");
        OutputStream os = conn.getOutputStream();
        os.write(param.getBytes(charsetName));
        os.flush();
        os.close();
        input = conn.getInputStream();
        rv = TohoursUtils.inputStream2String(input, charsetName);
    } finally {
        if (input != null) {
            input.close();
        }
    }
    return rv;
}

From source file:hashengineering.digitalcoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getBlockchainInfo() {
    try {//from w w  w  . ja  v  a 2  s.  c om
        Double btcRate = 0.0;

        Object result = getCoinValueBTC();

        if (result == null)
            return null;

        else
            btcRate = (Double) result;

        final URL URL = new URL("https://blockchain.info/ticker");
        final HttpURLConnection connection = (HttpURLConnection) URL.openConnection();
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.connect();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
            return null;

        Reader reader = null;
        try {
            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>();

            //Add Bitcoin information
            rates.put(CoinDefinition.cryptsyMarketCurrency,
                    new ExchangeRate(CoinDefinition.cryptsyMarketCurrency,
                            Utils.toNanoCoins(String.format("%.8f", btcRate).replace(",", ".")),
                            "pubapi.cryptsy.com"));

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                final JSONObject o = head.getJSONObject(currencyCode);
                //final String rate = o.optString("15m", null);

                double rateForBTC = o.getDouble("15m") * btcRate;

                final String rate = String.format("%.8f", rateForBTC); //o.optString("15m", null);

                if (rate != null) {
                    try {
                        rates.put(currencyCode, new ExchangeRate(currencyCode,
                                Utils.toNanoCoins(rate.replace(",", ".")), URL.getHost()));
                    } catch (final ArithmeticException x) {
                        log.debug("problem reading exchange rate: " + currencyCode, x);
                    }
                }
            }

            return rates;
        } finally {
            if (reader != null)
                reader.close();
        }
    } catch (final Exception x) {
        log.debug("problem reading exchange rates", x);
    }

    return null;
}

From source file:com.google.api.ads.adwords.awreporting.server.appengine.exporter.ReportExporterAppEngine.java

public static void html2PdfOverNet(InputStream htmlSource, ReportWriter reportWriter) {
    try {/*  w w  w . j  a  v  a2  s  .com*/
        URL url = new URL(HTML_2_PDF_SERVER_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/html");
        connection.setRequestProperty("charset", "utf-8");
        connection.setUseCaches(false);

        DataOutputStream send = new DataOutputStream(connection.getOutputStream());
        send.write(IOUtils.toByteArray(htmlSource));
        send.flush();

        // Read from connection
        reportWriter.write(connection.getInputStream());

        send.close();

        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:LNISmokeTest.java

/**
 * Get an item with WebDAV GET http request.
 * //from   w w w . j  a  v a2s  .com
 * @param lni the lni
 * @param itemHandle the item handle
 * @param packager the packager
 * @param output the output
 * @param endpoint the endpoint
 * 
 * @throws RemoteException the remote exception
 * @throws ProtocolException the protocol exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws FileNotFoundException the file not found exception
 */
private static void doGet(LNISoapServlet lni, String itemHandle, String packager, String output,
        String endpoint)
        throws java.rmi.RemoteException, ProtocolException, IOException, FileNotFoundException {
    // assemble URL from chopped endpoint-URL and relative URI
    String itemURI = doLookup(lni, itemHandle, null);
    URL url = LNIClientUtils.makeDAVURL(endpoint, itemURI, packager);
    System.err.println("DEBUG: GET from URL: " + url.toString());

    // connect with GET method, then copy file over.
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    fixBasicAuth(url, conn);
    conn.connect();
    int status = conn.getResponseCode();
    if (status < 200 || status >= 300) {
        die(status, "HTTP error, status=" + String.valueOf(status) + ", message=" + conn.getResponseMessage());
    }

    InputStream in = conn.getInputStream();
    OutputStream out = new FileOutputStream(output);
    copyStream(in, out);
    in.close();
    out.close();

    System.err.println("DEBUG: Created local file " + output);
    System.err.println(
            "RESULT: Status=" + String.valueOf(conn.getResponseCode()) + " " + conn.getResponseMessage());
}

From source file:hashengineering.digitalcoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getBitcoinCharts() {
    try {/*from   w w  w  .  j ava2 s .  com*/
        Double btcRate = 0.0;

        Object result = getCoinValueBTC();

        if (result == null)
            return null;

        else
            btcRate = (Double) result;

        final URL URL = new URL("http://api.bitcoincharts.com/v1/weighted_prices.json");
        final HttpURLConnection connection = (HttpURLConnection) URL.openConnection();
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.connect();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
            return null;

        Reader reader = null;
        try {
            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>();

            //Add Bitcoin information
            rates.put(CoinDefinition.cryptsyMarketCurrency,
                    new ExchangeRate(CoinDefinition.cryptsyMarketCurrency,
                            Utils.toNanoCoins(String.format("%.8f", btcRate).replace(",", ".")),
                            "pubapi.cryptsy.com"));

            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);
                    String rate = o.optString("24h", null);
                    if (rate == null)
                        rate = o.optString("7d", null);
                    if (rate == null)
                        rate = o.optString("30d", null);

                    double rateForBTC = Double.parseDouble(rate);

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

                    if (rate != null) {
                        try {
                            rates.put(currencyCode, new ExchangeRate(currencyCode,
                                    Utils.toNanoCoins(rate.replace(",", ".")), URL.getHost()));
                        } catch (final ArithmeticException x) {
                            log.debug("problem reading exchange rate: " + currencyCode, x);
                        }
                    }
                }
            }

            return rates;
        } finally {
            if (reader != null)
                reader.close();
        }
    } catch (final Exception x) {
        log.debug("problem reading exchange rates", x);
    }

    return null;
}

From source file:com.heraldapp.share.facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * //from w  ww.  j a  v a  2  s  .c  om
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url
 *            - the resource to open: must be a welformed URL
 * @param method
 *            - the HTTP method to use ("GET", "POST", etc.)
 * @param params
 *            - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException
 *             - if the URL format is invalid
 * @throws IOException
 *             - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    String response = "";
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("User-Agent",
                System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(10000);
        if (!method.equals("GET")) {
            // use method override
            params.putString("method", method);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8"));
        }

        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    } catch (SocketTimeoutException e) {
        return response;
    }
    return response;
}

From source file:Main.java

/**
 * Issue a POST request to the server./* w w w.  j ava  2  s . c o m*/
 *
 * @param endpoint
 *            POST address.
 * @param params
 *            request parameters.
 *
 * @throws java.io.IOException
 *             propagated from POST.
 */
public static String post(String endpoint, Map<String, String> params) throws IOException {
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }

        // Get Response
        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');
        }
        rd.close();
        return response.toString();

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