Created
July 19, 2011 16:31
-
-
Save oparrish/1092990 to your computer and use it in GitHub Desktop.
Downloading Facebook profile picture
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static final String PROFILE_PICTURE_URL = "https://graph.facebook.com/%s/picture?type=large&access_token=%s"; | |
private String downloadFacebookProfilePicture(String uid, String accessToken, String username) throws MalformedURLException, IOException { | |
//Get the picture url | |
HttpURLConnection.setFollowRedirects(false); | |
String profilePictureUrlString = new URL(String.format(PROFILE_PICTURE_URL, uid, accessToken)).openConnection().getHeaderField( | |
"location"); | |
//Set up temp location for picture | |
String fileExtension = StringUtils.substring(profilePictureUrlString, | |
StringUtils.lastIndexOf(profilePictureUrlString, ".") + 1); | |
String tempFilePath = (new StringBuilder(String.valueOf(System | |
.getProperty("java.io.tmpdir")))) | |
.append(StringUtils.replace(username, ".", "_")).append(".") | |
.append(fileExtension).toString(); | |
String exportUrl = profilePictureUrlString; | |
//Download file to temp location | |
downloadFile(exportUrl, tempFilePath); | |
return tempFilePath; | |
} | |
private void downloadFile(String exportUrl, String filepath) | |
throws IOException, MalformedURLException { | |
InputStream inStream = new URL(exportUrl).openStream(); | |
FileOutputStream outStream = new FileOutputStream(filepath); | |
copyStreams(inStream, outStream); | |
} | |
private void copyStreams(InputStream inStream, OutputStream outStream) | |
throws IOException { | |
try { | |
int c; | |
while ((c = inStream.read()) != -1) { | |
outStream.write(c); | |
} | |
} finally { | |
if (inStream != null) { | |
inStream.close(); | |
} | |
if (outStream != null) { | |
outStream.flush(); | |
outStream.close(); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment