今天遇到一个神奇的BUG,一个终端去下载一张图片,出现了504 Bad Gateway Timeout错误,把同样的url放到PC浏览器上又能正常打开,最后问题是解决了,但是具体原因还没搞清楚。
望有高人看到指点一下
出现问题的代码如下:
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); bis.mark(1024); byte[] buffer = new byte[1024]; bis.read(buffer); String orientation = parseOrientation(buffer); // decode bitmap size bis.reset(); bis.mark(bis.available()); Options options = new Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(bis, null, options); // decode scaled bitmap bis.reset(); options.inSampleSize = calculateScaleSize(options.outWidth, options.outHeight); options.inJustDecodeBounds = false; Bitmap scaleBitmap = BitmapFactory.decodeStream(bis, null, options); bis.close(); is.close(); }
经过多次尝试后,下面代码可以正常下载到图片:
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[10240]; int length; while ((length = is.read(buffer)) > -1) { baos.write(buffer, 0, length); } baos.flush(); Log.d(TAG, "download finish: " + baos.size()); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); baos.close(); is.close(); bais.mark(1024); buffer = new byte[1024]; bais.read(buffer); String orientation = parseOrientation(buffer); // decode bitmap size bais.reset(); bais.mark(bais.available()); Options options = new Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(bais, null, options); // decode scaled bitmap bais.reset(); options.inSampleSize = calculateScaleSize(options.outWidth, options.outHeight); options.inJustDecodeBounds = false; Bitmap scaleBitmap = BitmapFactory.decodeStream(bais, null, options); bais.close(); is.close(); }
两种写法唯一的区别就是方法一是拿到InputStream后直接Decode,方法二是先把数据下载到内存然后Decode,为啥方法一就会出现“504 Bad Gateway Timeout”呢?