由于证书错误,我无法使用HTTPS协议下载图像。这种情况发生在几周或更长时间,在此之前,我没有任何问题。
如果我使用HttpCommons Apache库,则错误是“主机名证书不匹配”,如果我使用URL和URLConnection,则例外是“证书未经过验证”。
我很绝望,因为我需要完成这项工作才能完成我的项目,而且我测试的所有项目都没有用。
这是Apache库的代码:
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
try
{
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
HttpEntity entity = response.getEntity();
if (entity != null)
{
try
{
byte[] data = EntityUtils.toByteArray(entity);
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
//bitmap = BitmapFactory.decodeStream(entity.getContent());
} catch (IOException e)
{
e.printStackTrace();
Log.e("FACEBOOKLIBRARY", "Error fetching image from this URL: " + url
+ "because of the download is corrupted");
bitmap = null;
} finally
{
entity.consumeContent();
}
}
}
else
{
Log.e("FACEBOOKLIBRARY", "Error fetching image from this URL: " + url
+ " because of the error: " + response.getStatusLine().toString());
bitmap = null;
}
} catch (IOException e)
{
e.printStackTrace();
Log.e("FACEBOOKLIBRARY", "Error fetching image while connecting to this URL: " + url);
bitmap = null;
}
return bitmap;
这是网址代码:
try {
URL u = new URL(url);
URLConnection connection = u.openConnection();
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while((current = bis.read()) != -1) {
baf.append(current);
}
byte[] byteArray = baf.toByteArray();
bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
bitmap = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
bitmap = null;
}
答案 0 :(得分:1)
我最终不得不停用主机名检查HttpClient执行此操作:
HttpClient client = new DefaultHttpClient();
SSLSocketFactory sf = (SSLSocketFactory) client.getConnectionManager().getSchemeRegistry().getScheme("https").getSocketFactory();
sf.setHostnameVerifier(new AllowAllHostnameVerifier());