我想用他的网址下载一个文件。我使用带有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时,下载文件就会启动。
先感谢您。
原因应该是您没有设置User-Agent:
connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:221.0) Gecko/20100101 Firefox/31.0"); // add this line to your code
connection.connect();
HTTP 403 Forbidden问题在哪里
错误代码清楚地说明了 - 您被禁止访问服务器上的资源。也许你需要先验证,也许你只是被禁止。很多可能性。