【发布时间】:2020-04-17 04:46:11
【问题描述】:
我在 Android 中下载图像时遇到问题。
有问题的图片链接: https://via.placeholder.com/150/92c952
我可以使用邮递员成功下载图像(200)。 但是当我使用 HttpConnection 在 Android 中编码时,它会以错误状态代码 410 响应我。 (然后触发 FileNotFounedException。)
下面是我的代码,
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int bytesRead = -1;
byte[] buffer = new byte[1024];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
httpConn.disconnect();
return outputStream.toByteArray();
} else {
httpConn.disconnect();
throw new RuntimeException("Error code: " + responseCode);
}
我的代码可以从 Imgur 成功下载图片,但是这个链接失败了。
请分享任何想法,我非常感谢!
【问题讨论】:
标签: java android https httpconnection