Java获取网络图片

public class ImageRequest {

    public static void main(String[] args) throws Exception{
        URL url = new URL(
            "http://a.hiphotos.baidu.com/image/pic/item/b3b7d0a20cf431adb35c8e304936acaf2edd9829.jpg");
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5 * 1000);
        InputStream inputStream = conn.getInputStream();//通过输入流获取图片数据
        byte[] data = readInputStream(inputStream);//得到图片的二进制数据
        File imageFile = new File("test.jpg");
        FileOutputStream fileOutputStream = new FileOutputStream(imageFile);
        fileOutputStream.write(data);
        fileOutputStream.close();
    }

    public static byte[] readInputStream(InputStream inputStream) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);//写到内存
        }
        inputStream.close();
        return outputStream.toByteArray();
    }

}