Mic*_*ico 1 android httpurlconnection http-status-code-403 android-asynctask
我想用他的网址下载一个文件。我将 AsyncTask 与 HttpURLConnection 一起使用,但是当我收到响应代码时,服务器返回错误 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;
}
Run Code Online (Sandbox Code Playgroud)
问题出在哪儿 ?
知道当我在浏览器中获取 URL 时,下载文件就会启动。
先感谢您。
小智 5
原因应该是你没有设置用户代理:
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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4396 次 |
| 最近记录: |