HttpURLConnection:服务器返回HTTP 403 Forbidden

时间:2014-11-17 09:36:14

标签: android android-asynctask httpurlconnection http-status-code-403

我想用他的网址下载一个文件。 我使用带有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时,下载文件会启动。

提前谢谢。

2 个答案:

答案 0 :(得分:2)

原因应该是您没有设置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();

答案 1 :(得分:0)

  

HTTP 403禁止   问题出在哪里

错误代码清楚地表明 - 您被禁止访问服务器上的资源。也许你需要先验证,也许你只是被禁止。很多可能性。