如何从Mediafire下载文件并将其存储到App文件夹中?

时间:2019-03-08 17:38:50

标签: android download mediafire

我们可以下载文件MediaFire吗?我正在尝试使用以下代码从MediaFire下载文件,但似乎无法正常工作。

当我在代码中传递直接链接时,我的代码有效,但对于 MediaFire 而言,它不起作用。因为没有Mediafire的直接下载链接,但是在下载按钮中有链接,但是此链接在每次重新加载网页时生成。我可以通过解析获得此链接吗?

有人可以帮我从MediaFire下载文件吗?

这是我的代码-

public class MainActivity extends AppCompatActivity {

public Button download;
public HttpURLConnection connection;
public URL url;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    download = findViewById(R.id.download);

    download.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplicationContext(), "Downloading..........\n", Toast.LENGTH_LONG).show();
            new task().execute();
            Toast.makeText(getApplicationContext(), "Download completed..........\n", Toast.LENGTH_LONG).show();
        }
    });


}

class task extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... voids) {
        try {
            url = new URL("http://www.mediafire.com/file/9074ul9m7cpcq0j/Sample+-+Menage+Quad+-+Oh+Dear.mp3");
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.connect();
            connection.setRequestMethod("GET");

            try {
                File mydir = getApplicationContext().getDir("Songs", Context.MODE_PRIVATE);
                if (!mydir.exists()) {
                    mydir.mkdir();
                }
                final File file = new File(mydir, "test.mp3");
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                InputStream inputStream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int bufferLength = 0;

                while ((bufferLength = inputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, bufferLength);
                }
                fileOutputStream.close();
                connection.disconnect();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
    }
}
}

0 个答案:

没有答案