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:com.entertailion.android.slideshow.utils.Utils.java

/**
 * Create a bitmap from a image URL./* w  w  w.ja va 2  s . c o m*/
 * 
 * @param src
 * @return
 */
public static final Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        int size = Math.max(myBitmap.getWidth(), myBitmap.getHeight());
        Bitmap b = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        c.drawBitmap(myBitmap, (size - myBitmap.getWidth()) / 2, (size - myBitmap.getHeight()) / 2, paint);
        return b;
    } catch (Exception e) {
        Log.e(LOG_TAG, "Faild to get the image from URL:" + src, e);
        return null;
    }
}

From source file:localSPs.SpiderOakAPI.java

public static String connectWithREST(String url, String method)
        throws IOException, ProtocolException, MalformedURLException {
    String newURL = "";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // Connect with a REST Method: GET, DELETE, PUT
    con.setRequestMethod(method);/* www.  j  ava 2  s. c om*/
    //add request header
    con.setReadTimeout(20000);
    con.setConnectTimeout(20000);
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    if (method.equals(DELETE) || method.equals(PUT))
        con.addRequestProperty("Authorization", "Base M5XWW5JNONZWUMSANBXXI3LBNFWC4Y3PNU5E2NDSNFXTEMZVJ5QWW");

    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:eu.liveandgov.ar.utilities.Download_Data.java

/**                      DownAndCopy
 * //  ww w  . java  2 s .c o  m
 * Download file from URL and Copy to Android file system folder
 * 
 * @param fileUrl
 * @param StringAndroidPath
 */
public static boolean DownAndCopy(String fileUrlSTR, String StringAndroidPath, boolean preservefilename,
        String Caller) {

    if (compareRemoteWithLocal(fileUrlSTR, StringAndroidPath)) {
        //Log.e("fileUrlSTR", "SKIP WITH HASH");
        return true;
    } else {
        Log.e("TRY TO DOWNLOAD BY " + Caller, fileUrlSTR);
    }

    SimpleDateFormat sdf = new SimpleDateFormat("mm");

    // Check if downloaded at least just 2 minutes ago
    for (String[] mem : MemDown)
        if (fileUrlSTR.equals(mem[0])) {
            int diff = Integer.parseInt(sdf.format(new Date())) - Integer.parseInt(mem[1]);
            Log.e("diff", " " + diff);
            if (diff < 2) {
                Log.d("Download_Data", "I am not downloading " + fileUrlSTR + " because it was downloaded "
                        + diff + " minutes ago");
                return true;
            }
        }

    if (!OS_Utils.exists(fileUrlSTR)) {
        Log.e("Download_Data", "URL: " + fileUrlSTR + " called from " + Caller + " not exists to copy it to "
                + StringAndroidPath);
        return false;
    }

    int DEBUG_FLAG = 0;

    HttpURLConnection conn;
    URL fileUrl = null;
    try {
        fileUrl = new URL(fileUrlSTR);
    } catch (MalformedURLException e1) {
        return false;
    }

    try {
        conn = (HttpURLConnection) fileUrl.openConnection();

        DEBUG_FLAG = 1;

        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(100);

        DEBUG_FLAG = 2;

        int current = 0;
        byte[] buffer = new byte[10];
        while ((current = bis.read(buffer)) != -1)
            baf.append(buffer, 0, current);

        DEBUG_FLAG = 3;

        /* Convert the Bytes read to a String. */
        File fileAndroid;

        try {

            if (preservefilename) {
                int iSlash = fileUrlSTR.lastIndexOf("/");
                fileAndroid = new File(StringAndroidPath + "/" + fileUrlSTR.substring(iSlash + 1));
            } else
                fileAndroid = new File(StringAndroidPath);

        } catch (Exception e) {
            Log.e("Download_Data.DownAndCopy", "I can not create " + StringAndroidPath);
            bis.close();
            conn.disconnect();
            return false;
        }

        DEBUG_FLAG = 4;

        FileOutputStream fos = new FileOutputStream(fileAndroid);
        fos.write(baf.toByteArray());

        DEBUG_FLAG = 5;

        bis.close();
        fos.close();
        conn.disconnect();

        MemDown.add(new String[] { fileUrlSTR, sdf.format(new Date()) });

        return true; //returns including the filename
    } catch (IOException e) {
        Log.e("Download_Data", "Download_Data: Error when trying to download:  " + fileUrl.toString() + " to "
                + StringAndroidPath + " DEBUG_FLAG=" + DEBUG_FLAG);
        return false;
    }

}

From source file:com.choices.imagecompare.urlsfetcher.ImageUrlsFetcher.java

@Nullable
private static String downloadContentAsString(String urlString) throws IOException {
    InputStream is = null;/*w  w w  . j ava2  s .  co m*/
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", IMGUR_CLIENT_ID);
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        if (response != SC_OK) {
            FLog.e(TAG, "Album request returned %s", response);
            return null;
        }
        is = conn.getInputStream();
        return readAsString(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:Main.java

public static String callJsonAPI(String urlString) {
    // Use HttpURLConnection as per Android 6.0 spec, instead of less efficient HttpClient
    HttpURLConnection urlConnection = null;
    StringBuilder jsonResult = new StringBuilder();

    try {//from www. j a v a  2s.c  o m
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(TIMEOUT_CONNECTION);
        urlConnection.setReadTimeout(TIMEOUT_READ);
        urlConnection.connect();

        int status = urlConnection.getResponseCode();

        switch (status) {
        case 200:
        case 201:
            BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

            String line;
            while ((line = br.readLine()) != null) {
                jsonResult.append(line).append("\n");
            }
            br.close();
        }
    } catch (MalformedURLException e) {
        System.err.print(e.getMessage());
        return e.getMessage();
    } catch (IOException e) {
        System.err.print(e.getMessage());
        return e.getMessage();
    } finally {
        if (urlConnection != null) {
            try {
                urlConnection.disconnect();
            } catch (Exception e) {
                System.err.print(e.getMessage());
            }
        }
    }
    return jsonResult.toString();
}

From source file:io.github.retz.web.JobRequestRouter.java

private static String fetchHTTP(String addr, int retry) throws MalformedURLException, IOException {
    LOG.debug("Fetching {}", addr);
    HttpURLConnection conn = null;
    try {/*from w w w  .j  a v a2s  .c  o m*/
        conn = (HttpURLConnection) new URL(addr).openConnection();
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        LOG.debug(conn.getResponseMessage());

    } catch (MalformedURLException e) {
        LOG.error(e.toString());
        throw e;
    } catch (IOException e) {
        LOG.error(e.toString());
        throw e;
    }

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), UTF_8))) {
        StringBuilder builder = new StringBuilder();
        String line;
        do {
            line = reader.readLine();
            builder.append(line);
        } while (line != null);
        LOG.debug("Fetched {} bytes from {}", builder.toString().length(), addr);
        return builder.toString();

    } catch (FileNotFoundException e) {
        throw e;
    } catch (IOException e) {
        // Somehow this happens even HTTP was correct
        LOG.debug("Cannot fetch file {}: {}", addr, e.toString());
        // Just retry until your stack get stuck; thanks to SO:33340848
        // and to that crappy HttpURLConnection
        if (retry < 0) {
            LOG.error("Retry failed. Last error was: {}", e.toString());
            throw e;
        }
        return fetchHTTP(addr, retry - 1);
    } finally {
        conn.disconnect();
    }

}

From source file:com.reactivetechnologies.jaxrs.RestServerTest.java

static String sendGet(String url) throws IOException {

    StringBuilder response = new StringBuilder();
    HttpURLConnection con = null;
    BufferedReader in = null;// www.j a v  a  2s . c o m
    try {
        URL obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        //add request header
        con.setRequestProperty("User-Agent", "Mozilla/5.0");

        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        } else {
            throw new IOException("Response Code: " + responseCode);
        }

        return response.toString();
    } catch (IOException e) {
        throw e;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {

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

}

From source file:com.dynamobi.db.conn.couchdb.CouchUdx.java

/**
 * Helper function gets the rows from the foreign CouchDB server and returns
 * them as a JSONArray./*from  ww  w. j  a  va 2  s . c  om*/
 */
private static InputStreamReader getViewStream(String user, String pw, String url, String view, String limit,
        boolean reduce, String groupLevel, boolean hasReducer) throws SQLException {
    String full_url = "";
    try {
        // TODO: stringbuffer this for efficiency
        full_url = makeUrl(url, view);
        String sep = (view.indexOf("?") == -1) ? "?" : "&";
        if (limit != null && limit.length() > 0) {
            full_url += sep + "limit=" + limit;
            sep = "&";
        }

        // These options only apply if a reducer function is present.
        if (hasReducer) {
            if (!reduce) {
                full_url += sep + "reduce=false";
                if (sep.equals("?"))
                    sep = "&";
            }
            if (groupLevel.toUpperCase().equals("EXACT"))
                full_url += sep + "group=true";
            else if (groupLevel.toUpperCase().equals("NONE"))
                full_url += sep + "group=false";
            else
                full_url += sep + "group_level=" + groupLevel;
        }

        logger.log(Level.FINE, "Attempting CouchDB request with URL: " + full_url);

        URL u = new URL(full_url);
        HttpURLConnection uc = (HttpURLConnection) u.openConnection();
        if (user != null && user.length() > 0) {
            uc.setRequestProperty("Authorization", "Basic " + buildAuthHeader(user, pw));
        }
        uc.connect();
        return new InputStreamReader(uc.getInputStream());

    } catch (MalformedURLException e) {
        throw new SQLException("Bad URL: " + full_url);
    } catch (IOException e) {
        if (hasReducer) { // try again but without the reduce args..
            try {
                return getViewStream(user, pw, url, view, limit, reduce, groupLevel, false);
            } catch (SQLException e2) { // No good.

            }
        }
        throw new SQLException("Could not read data from URL: " + full_url);
    }
}

From source file:edu.samplu.common.ITUtil.java

public static String getHTML(String urlToRead) {
    URL url;/*from   w ww. j a  v a  2s. c om*/
    HttpURLConnection conn;
    BufferedReader rd;
    String line;
    String result = "";

    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = rd.readLine()) != null) {
            result += line;
        }
        rd.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}

From source file:Main.java

public static String[] getUrlInfos(String urlAsString, int timeout) {
    try {/*from  w  w w  .  ja v a  2 s. co m*/
        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 Gecko/20100915 Firefox/3.6.10");

        // on android we got problems because of this
        // so disable that for now
        //            hConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        hConn.setConnectTimeout(timeout);
        hConn.setReadTimeout(timeout);
        // default length of bufferedinputstream is 8k
        byte[] arr = new byte[K4];
        InputStream is = hConn.getInputStream();

        if ("gzip".equals(hConn.getContentEncoding()))
            is = new GZIPInputStream(is);

        BufferedInputStream in = new BufferedInputStream(is, arr.length);
        in.read(arr);

        return getUrlInfosFromText(arr, hConn.getContentType());
    } catch (Exception ex) {
    }
    return new String[] { "", "" };
}