Skip to content

Instantly share code, notes, and snippets.

@oparrish
Created July 19, 2011 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oparrish/1092990 to your computer and use it in GitHub Desktop.
Save oparrish/1092990 to your computer and use it in GitHub Desktop.
Downloading Facebook profile picture
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