java.net.URL read stream to byte[]

后端 未结 8 478
失恋的感觉
失恋的感觉 2020-11-29 03:11

I`m trying to read an image from an URL (with the java package java.net.URL) to a byte[]. \"Everything\" works fine, except that the content isnt being ent

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 03:45

    I am very surprised that nobody here has mentioned the problem of connection and read timeout. It could happen (especially on Android and/or with some crappy network connectivity) that the request will hang and wait forever.

    The following code (which also uses Apache IO Commons) takes this into account, and waits max. 5 seconds until it fails:

    public static byte[] downloadFile(URL url)
    {
        try {
            URLConnection conn = url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.connect(); 
    
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(conn.getInputStream(), baos);
    
            return baos.toByteArray();
        }
        catch (IOException e)
        {
            // Log error and return null, some default or throw a runtime exception
        }
    }
    

提交回复
热议问题