【发布时间】:2014-11-17 09:36:14
【问题描述】:
我想用他的 url 下载一个文件。 我使用带有 HttpURLConnection 的 AsyncTask,但是当我得到响应代码时,服务器返回错误 403。 我在 doInBackground 中使用 HttpURLConnection。
代码:
@Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
ext = FilenameUtils.getExtension(sUrl[0]);
fileName = FilenameUtils.getBaseName(sUrl[0]);
Log.i("Brieg", "storage : /storage/emulated/0/" + fileName + "." + ext);
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage();
}
int fileLength = connection.getContentLength();
input = connection.getInputStream();
output = new FileOutputStream("/storage/emulated/0/" + fileName + "." + ext);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
if (isCancelled()) {
input.close();
return null;
}
total += count;
if (fileLength > 0)
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
}
catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
}
catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
问题出在哪里?
知道当我在浏览器中获取 URL 时,下载文件就会启动。
提前谢谢你。
【问题讨论】:
-
sUrl[0]请显示您的网址的样子。 -
output = new FileOutputStream("/storage/emulated/0/" + fileName + "." + ext);。使用这样的硬编码路径并不好。它会在许多设备上失败。它是什么样的服务器?它驻留在哪里(局域网/互联网)? -
我知道,我只是用它来测试但应用程序之前停止了。网址是这样的:mywebsite.com/myfile.epub
标签: android android-asynctask httpurlconnection http-status-code-403