2011-05-21 66 views
1

由于证书错误,我无法使用HTTPS协议下载图像。这发生了几个星期或更长的时间,在此之前,我没有任何问题。使用Android的HTTPS从Facebook Graph API下载图像时出错

如果我使用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; 

这是URL代码:

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

回答

1

最后我不得不停用主机名检查HttpClient的这样做:

HttpClient client = new DefaultHttpClient(); 

SSLSocketFactory sf = (SSLSocketFactory) client.getConnectionManager().getSchemeRegistry().getScheme("https").getSocketFactory(); 
sf.setHostnameVerifier(new AllowAllHostnameVerifier());