在Android

时间:2015-07-22 06:50:03

标签: java android url

我有一个网址https://www.youtube.com/watch?v=mGhQTs3F1O4&spf=prefetch,当我在浏览器中打开它时会下载一个包含视频信息的文件。

在浏览器中运行良好,但我无法在Android中实现..当我尝试使用以下代码下载文件时,我得到了html文件..

private class DownloadTask extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... sUrl) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        String path = Environment.getExternalStorageDirectory().getPath()
                + "/" + sUrl[1];
        Log.d(TAG, "PATH: " + path);
        try {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP "
                        + connection.getResponseCode() + " "
                        + connection.getResponseMessage();
            }

            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength();

            // download the file
            input = connection.getInputStream();
            output = new FileOutputStream(path);

            byte data[] = new byte[4096];
            int count;
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled()) {
                    input.close();
                    return null;
                }

                output.write(data, 0, count);
            }
        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }

            if (connection != null)
                connection.disconnect();
        }
        return path;
    }
}

那么..有什么想法吗?

2 个答案:

答案 0 :(得分:0)

编辑而不使用已弃用的类:

他们似乎检查了用户代理,因此您必须将其设置为:

connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0")
connection.connect();

老答案: 对我来说,它适用于使用HTTPClient而不是HTTPConnection(在我看来,对于这种情况,没有理由使用后一类)

以下是一个例子:

@Override
protected String doInBackground(String... sUrl) {
    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(sUrl[0]);
    try {
        URL url = new URL(sUrl[0]);
        HttpResponse resp = client.execute(get);
        return EntityUtils.toString(resp.getEntity());

    } catch (Exception e) {
            return e.toString();
    }
}

您还应该考虑使用RetroFit

答案 1 :(得分:0)

请尝试以下代码:

form_valid