我需要从 URL 加载和更新图像,并且 url 由 .htaccess 验证
有谁知道如何访问此图像文件
我的问题是:- 访问此类文件时如何设置凭据(在 HttpUrlConnection 中)
我需要从 URL 加载和更新图像,并且 url 由 .htaccess 验证
有谁知道如何访问此图像文件
我的问题是:- 访问此类文件时如何设置凭据(在 HttpUrlConnection 中)
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 对象,我能够毫无问题地提取照片资源。
如果是基本身份验证,只需使用身份验证器(注意,这仅适用于 GET 请求)
Authenticator.setDefault(new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("myuser","mypass".toCharArray());
}});
然后让你的 HttpURLConnection 低于它。