在Android中访问经过身份验证的URl图像

时间:2011-06-20 12:49:57

标签: android url authentication bitmapimage

我需要加载,并从URL更新图像,并通过.htaccess验证网址

是否有人知道如何访问此图像文件

我的问题是: - 访问此类文件时如何设置凭据(在HttpUrlConnection中)

2 个答案:

答案 0 :(得分:1)

Bitmap bmImg;
public Bitmap downloadFile(String stringURL)
{
    try 
    {
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(myHtaccessUsername, myHTaccessPassword)); 
        HttpGet request = new HttpGet(stringURL);
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();
        bmImg = BitmapFactory.decodeStream(inputStream);
    } 
    catch (IOException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return bmImg;
}

这是我用来解决此问题的代码。我正在使用HttpUrlConnection从任何公共URL中提取照片,但当涉及到需要基本访问级别(htaccess凭据)的特定服务器时,由于HttpUrlConnection处理握手的方式,我无法使用HttpUrlConnection 。使用DefaultHttpClient以及HttpGet,HttpResponse和HttpEntity对象,我能够毫无问题地提取照片资源。

答案 1 :(得分:0)

如果是基本身份验证,只需使用身份验证器(注意,这仅适用于GET请求)

Authenticator.setDefault(new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication("myuser","mypass".toCharArray());
}});

然后将你的HttpURLConnection置于其下方。