开发者

accesing Authenticated URl of image in Android

I need to load, and update image开发者_如何学JAVA from URL and the url is authenticated by .htaccess

Does any one know how to get access to this image file

My question is:- how to set Credentials (in HttpUrlConnection ) when accessing such file


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;
}

This is the code that I used to solve this issue. I was using an HttpUrlConnection to pull photos from any public URL but when it came to a specific server that required a basic level of access (htaccess credentials) I could not use the HttpUrlConnection I assume because of the way a HttpUrlConnection handles the handshake or something. Using the DefaultHttpClient along with HttpGet, HttpResponse, and HttpEntity objects I was able to pull the photo resource with no problems.


If it's basic authentication, just use an authenticator (Note, this is only for a GET request)

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

then make your HttpURLConnection below that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜