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:Main.java

/**
 * Download the avatar image from the server.
 *
 * @param avatarUrl the URL pointing to the avatar image
 * @return a byte array with the raw JPEG avatar image
 *///from  w w w  .  j  a va2  s.c  o  m
public static byte[] downloadAvatar(final String avatarUrl) {
    // If there is no avatar, we're done
    if (TextUtils.isEmpty(avatarUrl)) {
        return null;
    }

    try {
        Log.i(TAG, "Downloading avatar: " + avatarUrl);
        // Request the avatar image from the server, and create a bitmap
        // object from the stream we get back.
        URL url = new URL(avatarUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        try {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            final Bitmap avatar = BitmapFactory.decodeStream(connection.getInputStream(), null, options);

            // Take the image we received from the server, whatever format it
            // happens to be in, and convert it to a JPEG image. Note: we're
            // not resizing the avatar - we assume that the image we get from
            // the server is a reasonable size...
            Log.i(TAG, "Converting avatar to JPEG");
            ByteArrayOutputStream convertStream = new ByteArrayOutputStream(
                    avatar.getWidth() * avatar.getHeight() * 4);
            avatar.compress(Bitmap.CompressFormat.JPEG, 95, convertStream);
            convertStream.flush();
            convertStream.close();
            // On pre-Honeycomb systems, it's important to call recycle on bitmaps
            avatar.recycle();
            return convertStream.toByteArray();
        } finally {
            connection.disconnect();
        }
    } catch (MalformedURLException muex) {
        // A bad URL - nothing we can really do about it here...
        Log.e(TAG, "Malformed avatar URL: " + avatarUrl);
    } catch (IOException ioex) {
        // If we're unable to download the avatar, it's a bummer but not the
        // end of the world. We'll try to get it next time we sync.
        Log.e(TAG, "Failed to download user avatar: " + avatarUrl);
    }
    return null;
}

From source file:Main.java

public static String requestPage(String urlPath) throws Exception {
    URL url = new URL(urlPath);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    int responseCode = connection.getResponseCode();
    if (responseCode != 200) {
        throw new Exception("Error loading page: " + responseCode + connection.getResponseMessage());
    }//from  ww  w.  j  av a  2s .  c om

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    String response = "";

    while ((inputLine = in.readLine()) != null) {
        response += inputLine;
    }

    in.close();
    return response;
}

From source file:com.ettoremastrogiacomo.sktradingjava.starters.Temp.java

public static String getYahooQuotes(String symbol) throws Exception {
    //http://real-chart.finance.yahoo.com/table.csv?s=ENEL.MI&d=0&e=26&f=2017&g=d&a=6&b=9&c=2001&ignore=.csv
    URL url = new URL("https://finance.yahoo.com/quote/" + symbol + "/history?p=" + symbol);

    HttpFetch http = new HttpFetch();
    String res = new String(http.HttpGetUrl(url.toString(), Optional.empty(), Optional.empty()));
    int k0 = res.indexOf("consent-form single-page-form single-page-agree-form");

    if (k0 > 0) {
        java.util.HashMap<String, String> pmap = new java.util.HashMap<>();
        Document dy = Jsoup.parse(res);
        Elements els = dy.select(
                "form[class='consent-form single-page-form single-page-agree-form'] input[type='hidden']");
        els.forEach((x) -> {//from ww w.j av  a  2 s . c o m
            pmap.put(x.attr("name"), x.attr("value"));
        });
        HttpURLConnection huc = http.sendPostRequest("https://guce.oath.com/consent", pmap);
        BufferedReader in = new BufferedReader(new InputStreamReader(huc.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        res = response.toString();
        //cookieList = cookieManager.getCookieStore().getCookies();

    }
    int k1 = res.indexOf("CrumbStore");
    int k2 = res.indexOf("\"", k1 + 22);
    String crumb = res.substring(k1 + 21, k2).replace("\"", "").replace("\\u00", "%");
    LOG.info("crumb=" + crumb);
    String u2 = "https://query1.finance.yahoo.com/v7/finance/download/" + symbol + "?period1=0&period2="
            + System.currentTimeMillis() + "&interval=1d&events=history&crumb=" + crumb;
    res = new String(http.HttpGetUrl(u2, Optional.empty(), Optional.of(http.getCookies())));
    LOG.debug("getting " + u2);
    LOG.debug(res);
    return res;
}

From source file:info.tongrenlu.android.helper.HttpHelper.java

static public JSONObject loadJSON(String url) {
    HttpURLConnection connection = null;
    JSONObject json = null;/*from  w  ww.  java2  s.c  o m*/
    InputStream is = null;

    try {
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(5000);

        is = new BufferedInputStream(connection.getInputStream());
        json = new JSONObject(convertStreamToString(is));
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (JSONException je) {
        je.printStackTrace();
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

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

    return json;
}

From source file:com.gabrielluz.megasenaanalyzer.MegaSenaAnalyzer.java

public static byte[] downloadFile(String fileUrl) throws IOException {
    java.net.CookieManager cm;/*  ww w.  j a  v a2  s  .com*/
    cm = new java.net.CookieManager();
    java.net.CookieHandler.setDefault(cm);
    URL url = new URL(fileUrl);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    int responseCode = httpConn.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        try (InputStream inputStream = httpConn.getInputStream()) {
            return MegaSenaAnalyzer.unZipIt(inputStream);
        }
    } else {
        System.out.println("No file to download. Server replied HTTP code: " + responseCode);
        httpConn.disconnect();
        return null;
    }
}

From source file:io.github.retz.scheduler.MesosHTTPFetcher.java

private static Optional<String> fetchDirectory(String slave, String frameworkId, String executorId) {
    try {/*from w w w .j  a va  2s. c om*/
        URL url = new URL("http://" + slave + "/state");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        return extractDirectory(conn.getInputStream(), frameworkId, executorId);

    } catch (MalformedURLException e) {
        // REVIEW: catch(MalformedURLException) clause can be removed because it <: IOException
        return Optional.empty();
    } catch (IOException e) {
        return Optional.empty();
    }
}

From source file:massbank.svn.MSDBUpdateUtil.java

/**
 *
 *//*from w w w.j ava  2s . c  om*/
public static boolean updateSubStructData(String serverUrl) {
    boolean ret = true;
    String cgiUrl = serverUrl + "cgi-bin/GenSubstructure.cgi";
    try {
        URL url = new URL(cgiUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(10 * 1000);
        con.setReadTimeout(60 * 1000);
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String line = "";
        StringBuilder res = new StringBuilder();
        while ((line = in.readLine()) != null) {
            res.append(line);
        }
        if (res.indexOf("OK") == -1) {
            ret = false;
        }
    } catch (IOException e) {
        e.printStackTrace();
        ret = false;
    }
    return ret;
}

From source file:com.mopaas_mobile.http.BaseHttpRequester.java

public static String doGET(String urlstr, List<BasicNameValuePair> params) throws IOException {
    String result = null;/*from  w ww  . j  av  a 2 s .c o  m*/
    String content = "";
    for (int i = 0; i < params.size(); i++) {
        content = content + "&" + URLEncoder.encode(((NameValuePair) params.get(i)).getName(), "UTF-8") + "="
                + URLEncoder.encode(((NameValuePair) params.get(i)).getValue(), "UTF-8");
    }
    URL url = new URL(urlstr + "?" + content.substring(1));
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);
    connection.setRequestMethod("GET");
    connection.setUseCaches(false);
    connection.connect();
    InputStream is = connection.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

    StringBuffer b = new StringBuffer();
    int ch;
    while ((ch = br.read()) != -1) {
        b.append((char) ch);
    }
    result = b.toString().trim();
    connection.disconnect();
    return result;
}

From source file:com.example.prathik1.drfarm.OCRRestAPI.java

private static void DownloadConvertedFile(String outputFileUrl) throws IOException {
        URL downloadUrl = new URL(outputFileUrl);
        HttpURLConnection downloadConnection = (HttpURLConnection) downloadUrl.openConnection();

        if (downloadConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

            InputStream inputStream = downloadConnection.getInputStream();

            // opens an output stream to save into file
            FileOutputStream outputStream = new FileOutputStream("C:\\converted_file.doc");

            int bytesRead = -1;
            byte[] buffer = new byte[4096];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }/*from   w  w w . j a  va  2s . c  o  m*/

            outputStream.close();
            inputStream.close();
        }

        downloadConnection.disconnect();
    }

From source file:cn.garymb.wechatmoments.common.OkHttpStack.java

@SuppressWarnings("deprecation")
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;//from  ww w . j a v  a  2 s  .  c om
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}