Как загрузить файл из защищенной веб-папки в приложении для Android? - PullRequest
0 голосов
/ 09 сентября 2011

Мне нужна помощь по загрузке файла изображения из папки, защищенной паролем, в мое приложение для Android. Код, который я имею, использует URLConnection вместе с getInputStream / BufferedInputStream, но я не вижу, как получить аутентификацию по имени пользователя / паролю там. Я вижу, что у HttpClient есть UsernamePasswordCredentials, но я не знаю, как загрузить файл с помощью HttpClient, так что это мне мало поможет.

Вот код, который я нашел до сих пор, как я могу скачать файл, используя это?

public class ClientAuthentication {

    public static void main(String[] args) throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope("localhost", 443),
                    new UsernamePasswordCredentials("username", "password"));

            HttpGet httpget = new HttpGet("https://localhost/protected");

            System.out.println("executing request" + httpget.getRequestLine());
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
    }
}

Или, у меня есть этот код для загрузки файла - как мне добавить к этому учетные данные:

http://www.helloandroid.com/tutorials/how-download-fileimage-url-your-device

Спасибо!

РЕДАКТИРОВАТЬ: ну, здесь не так много помощи. Я нашел этот ответ, который я собираюсь попробовать и переделать для моих целей: Скачать файл с DefaultHTTPClient и упреждающей аутентификацией

1 Ответ

2 голосов
/ 09 сентября 2011

Ну, это код, который я придумал, похоже, работает. Я публикую его, так как у меня было так много проблем с поиском подобного кода в Интернете. Я приветствую предложения о том, как его улучшить:)

public void downloadHTTPC(Activity act, String imageURL, String fileName) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        String pathDir = act.getExternalFilesDir(null).toString() + "/" + fileName;
        File file = new File(pathDir);
        long startTime = System.currentTimeMillis();
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(null, -1),
                new UsernamePasswordCredentials("user", "password"));

        HttpGet httpget = new HttpGet(IMGURL + imageURL);

        System.out.println("executing request" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
            InputStream is = entity.getContent();

            BufferedInputStream bis = new BufferedInputStream(is);

            /*
             * Read bytes to the Buffer until there is nothing more to read(-1).
             */
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }

            /* Convert the Bytes read to a Stream. */
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baf.toByteArray());
            fos.close();
            Log.d("ImageManager", "download ready in"
                    + ((System.currentTimeMillis() - startTime) / 1000)
                    + " sec");
        }

        //EntityUtils.consume(entity);
    } catch (IOException e) {
        Log.d("ImageManager", "Error: " + e);

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...