2011-07-23 23 views
2

我使用的代碼如下Facebook的虛擬形象現身的ImageView顯示頭像Facebook上的ImageView

@Override 

public void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    ImageView img = (ImageView) findViewById(R.id.imgAvatar); 
    img.setImageBitmap(getBitmapFromURL("http://graph.facebook.com/"+"100002394015528"+"/picture")); 
} 
public static Bitmap getBitmapFromURL(String src) { 
    try { 
     URL url = new URL(src); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setDoInput(true); 
     connection.connect(); 
     InputStream input = connection.getInputStream(); 
     Bitmap myBitmap = BitmapFactory.decodeStream(input); 
     return myBitmap; 
    } catch (IOException e) { 
     e.printStackTrace(); 
     return null; 
    } 
}` 

但它不能正常工作。請幫幫我。

回答

4

http://graph.facebook.com/id/picture不返回圖像。它返回一些響應頭,包括302重定向和位置頭。

你舉的例子,例如重定向到:http://profile.ak.fbcdn.net/hprofile-ak-snc4/211619_100002394015528_568817_q.jpg

所以不是

InputStream input = connection.getInputStream(); 
Bitmap myBitmap = BitmapFactory.decodeStream(input); 

你需要從請求獲得頭,按照位置,然後做你做之前。我不知道Android,或者是什麼語言。 (Java?)所以我無法幫助,但我認爲這可能是足夠的信息讓你朝着正確的方向前進。

+0

你不能更具體? –

1

使用此功能得到真正的URL發送給形象:

public static String getUrlFacebookUserAvatar(String name_or_idUser) 
{ 
    String address = "http://graph.facebook.com/"+name_or_idUser+"/picture"; 
    URL url; 
    String newLocation = null; 
    try { 
     url = new URL(address); 
     HttpURLConnection.setFollowRedirects(false); //Do _not_ follow redirects! 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     newLocation = connection.getHeaderField("Location"); 
    } catch (MalformedURLException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    return newLocation; 
}