我使用下面的代码,它不起作用。
当我在浏览器上使用imageUrl时,它会在某个地方重定向,然后才能正常工作
但我只有n个facebook id,每次重定向的url都不同。
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class SaveImageFromUrl {
public static void main(String[] args) throws Exception {
String imageUrl = "http://graph.facebook.com/67563683055/picture?type=square";
String destinationFile = "C:\\Users\\emtx\\Desktop\\Nxg-pic.png";
saveImage(imageUrl, destinationFile);
}
public static void saveImage(String imageUrl, String destinationFile) throws IOException {
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}
答案 0 :(得分:0)
您正在使用的地址将您重定向到其他位置。由于URL类不会自动重定向您所获得的内容
Location
指向新地址),您可能想要创建类似的方法(基于:http://www.mkyong.com/java/java-httpurlconnection-follow-redirect-example/)
public static String getFinalLocation(String address) throws IOException{
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
int status = conn.getResponseCode();
if (status != HttpURLConnection.HTTP_OK)
{
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
{
String newLocation = conn.getHeaderField("Location");
return getFinalLocation(newLocation);
}
}
return address;
}
并更改您的
URL url = new URL(imageUrl);
到
URL url = new URL(getFinalLocation(imageUrl));
答案 1 :(得分:0)
除了Phsemos答案,您还可以使用redirect
参数禁用重定向,并使用以下API调用将真实URL作为JSON:
https://graph.facebook.com/67563683055/picture?type=square&redirect=false
这就是JSON的样子:
{
"data": {
"is_silhouette": false,
"url": "https://scontent.xx.fbcdn.net/hprofile-xaf1/v/t1.0-1/c44.44.544.544/s50x50/316295_10151906553973056_2129080216_n.jpg?oh=04888b6ef5d631447227b42d82ebd35d&oe=57250EA4"
}
}