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

public static String getHtml(String getUrl, String charsetName) {
    String html = "";
    URL url;// www.ja v  a2 s  . com
    try {
        url = new URL(getUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-Agent", userAgent);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setReadTimeout(timeout);
        connection.setFollowRedirects(true);
        connection.connect();
        InputStream inStrm = connection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(inStrm, charsetName));
        String temp = "";

        while ((temp = br.readLine()) != null) {
            html = html + (temp + '\n');
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return html;
}

From source file:com.abid_mujtaba.bitcoin.tracker.network.Client.java

private static String get(String url_string) throws ClientException {
    HttpURLConnection connection = null; // NOTE: fetchImage is set up to use HTTP not HTTPS

    try {//from  w w w .ja v a2  s.c o  m
        URL url = new URL(url_string);
        connection = (HttpURLConnection) url.openConnection();

        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);

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

        int response_code;

        if ((response_code = connection.getResponseCode()) != 200) {
            throw new ClientException("Error code returned by response: " + response_code);
        }

        return InputStreamToString(is);
    } catch (SocketTimeoutException e) {
        throw new ClientException("Socket timed out.", e);
    } catch (IOException e) {
        throw new ClientException("IO Exception raised while attempting to GET response.", e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.androidzeitgeist.dashwatch.common.IOUtil.java

static String fetchPlainText(URL url) throws IOException {
    InputStream in = null;//from   ww  w  . j  ava2s .  c o m

    try {
        OkHttpClient client = new OkHttpClient();
        HttpURLConnection conn = client.open(url);
        conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
        conn.setReadTimeout(DEFAULT_READ_TIMEOUT);
        in = conn.getInputStream();
        return readFullyPlainText(in);

    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.android.dialer.omni.PlaceUtil.java

/**
 * Executes a GET request and return a JSON object
 * @param url The API URL//  w w  w  .jav  a 2s .  c om
 * @return the JSON object
 * @throws IOException
 * @throws JSONException
 */
public static JSONObject getJsonRequest(String url) throws IOException, JSONException {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("GET");

    if (DEBUG)
        Log.d(TAG, "Getting JSON from: " + url);

    con.setDoOutput(true);
    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

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

    JSONObject json = new JSONObject(response.toString());
    return json;
}

From source file:com.sunchenbin.store.feilong.core.net.URLConnectionUtil.java

/**
 *  input stream./*from ww w .ja  v a  2 s . c  om*/
 *
 * @param httpRequest
 *            the http request
 * @param connectionConfig
 *            the connection config
 * @return the input stream
 * @since 1.2.0
 * @see "org.springframework.core.io.UrlResource#getInputStream()"
 */
public static InputStream getInputStream(HttpRequest httpRequest, ConnectionConfig connectionConfig) {
    HttpURLConnection httpURLConnection = getHttpURLConnection(httpRequest, connectionConfig);
    try {
        return httpURLConnection.getInputStream();
    } catch (IOException e) {
        //???. disconnect() ????? HttpURLConnection .
        //? finally ?, ??inputstream

        // per Java's documentation, this is not necessary, and precludes keepalives. However in practise,
        // connection errors will not be released quickly enough and can cause a too many open files error.
        IOUtils.close(httpURLConnection); // Close the HTTP connection (if applicable). 

        throw new UncheckedIOException(e);
    }
}

From source file:jmc.util.UtlFbComents.java

public static String getJSONComentarios(String url, Long numComents) throws JMCException {
    String linea = "";
    String buf = "";

    try {// ww  w  .  j a va2  s . c  o m
        Properties props = ConfigPropiedades.getProperties("props_config.properties");
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        URL ur = new URL(
                "http://graph.facebook.com/comments?id=" + url + "&limit=" + numComents + "&filter=stream");
        HttpURLConnection cn = (HttpURLConnection) ur.openConnection();

        cn.setRequestProperty("user-agent", props.getProperty("navegador"));
        cn.setInstanceFollowRedirects(false);
        cn.setUseCaches(false);
        cn.connect();

        BufferedReader br = new BufferedReader(new InputStreamReader(cn.getInputStream()));

        while ((linea = br.readLine()) != null) {
            buf.concat(linea);
        }
        cn.disconnect();

    } catch (IOException e) {
        throw new JMCException(e);
    }
    return buf;
}

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesUtility.java

protected static String readHTTPConnection(HttpURLConnection conn)
        throws UnsupportedEncodingException, IOException {
    StringBuilder sb = new StringBuilder();
    BufferedReader br;/*from w  w w  .  ja  va2  s  .  c  o  m*/

    br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
    String line = null;
    while ((line = br.readLine()) != null) {
        sb.append(line + "\n");
    }
    br.close();

    return sb.toString();
}

From source file:de.jetwick.util.Translate.java

public static String download(String urlAsString) {
    try {//from w ww  . j ava 2  s  .com
        URL url = new URL(urlAsString);
        //using proxy may increase latency
        HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
        hConn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20100101 Firefox/7.0.1");
        hConn.addRequestProperty("Referer", "http://jetsli.de/crawler");

        hConn.setConnectTimeout(2000);
        hConn.setReadTimeout(2000);
        InputStream is = hConn.getInputStream();
        if ("gzip".equals(hConn.getContentEncoding()))
            is = new GZIPInputStream(is);

        return getInputStream(is);
    } catch (Exception ex) {
        return "";
    }
}

From source file:ilearnrw.utils.ServerHelperClass.java

public static String sendGet(String link) throws Exception {
    String url = baseUrl + link;// www .j  a v  a2s .c o  m
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // optional default is GET
    con.setRequestMethod("GET");
    con.setRequestProperty("Authorization", userNamePasswordBase64("api", "api"));
    //con.setRequestProperty("User-Agent", USER_AGENT);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    return response.toString();
}

From source file:com.manning.androidhacks.hack040.util.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.
 * /*from   w w  w.ja v a  2 s  . com*/
 * @param context
 *          The context to use
 * @param urlString
 *          The URL to fetch
 * @param cache
 *          The disk cache instance to get the download directory from.
 * @return A File pointing to the fetched bitmap
 */
public static File downloadBitmap(Context context, String urlString, DiskLruCache cache) {
    final File cacheFile = new File(cache.createFilePath(urlString));

    if (cache.containsKey(urlString)) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "downloadBitmap - found in http cache - " + urlString);
        }
        return cacheFile;
    }

    if (BuildConfig.DEBUG) {
        Log.d(TAG, "downloadBitmap - downloading - " + urlString);
    }

    Utils.disableConnectionReuseIfNecessary();
    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;

    try {
        final URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        final InputStream in = new BufferedInputStream(urlConnection.getInputStream(), Utils.IO_BUFFER_SIZE);
        out = new BufferedOutputStream(new FileOutputStream(cacheFile), Utils.IO_BUFFER_SIZE);

        int b;
        while ((b = in.read()) != -1) {
            out.write(b);
        }
        cache.putFromFetcher(urlString);
        return cacheFile;

    } catch (final IOException e) {
        Log.e(TAG, "Error in downloadBitmap - " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (out != null) {
            try {
                out.close();
            } catch (final IOException e) {
                Log.e(TAG, "Error in downloadBitmap - " + e);
            }
        }
    }

    return null;
}