2012-03-24 2 views
-3

HttpURLConnection을 통해 내 프로필에 사진을 업로드하려고합니다. 내 코드에서Java에서 HTTP 요청을 사용하여 Facebook 사진 업로드

샘플을 publish_stream의 액세스를가 user_status, user_photos, offline_access에 대한 토큰이 있습니다

url = new URL("https://graph.facebook.com/me/photos"); 

String content = 
    "access_token=" + URLEncoder.encode ("my_token") + 
    "&message=" + URLEncoder.encode ("SUNT !!!")+ 
    "&url=" + URLEncoder.encode("file:///D:\\personale\\Images\\P0030_07-02-11_00.JPG"); 

나는

{"error":{"message":"file:\/\/\/D:\\personale\\Images\\P0030_07-02-11_00.JPG is an internal url, but this is an external request.","type":"CurlUrlInvalidException"}} 

내가 업로드 할 수 다음과 같은 오류가 발생했습니다 요청을 할 때 내 PC에서 파일 URL을 사용하여 파일을? 파일에서 바이트 배열을 사용하여 파일을 업로드하려면 어떻게해야합니까?

감사합니다.

+0

[restfb] (http://restfb.com/) 또는 [spring-social-facebook] (http://static.springsource.org/spring-social-facebook/docs/1.0.x/reference/)을 확인하십시오. html /). 그래프 API의 자바 래퍼 (wrapper)로 일을 더 쉽게 만듭니다. – Bozho

+0

'url' 매개 변수는 공개적으로 액세스 할 수있는 외부 제공 이미지의 업로드 용으로 설계되었습니다. 로컬 이미지를 업로드하려면 ('url' 대신에) ['source'] (http://developers.facebook.com/docs/reference/api/user/#photos)를 사용해야하며'multipart/form- 데이터 부호화 된 화상 데이터이다. –

답변

1

The solution, as posted by dnp :


많은 감사합니다!

public class Main2 { 

static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy"; 

public static void main(String [] args) throws IOException{ 
    URL url; 
    HttpURLConnection urlConn; 
    DataOutputStream printout; 
    DataInputStream input; 

    //------------------------------------------------------------------- 

    File image = new File("D:/personale/Images/P1025[01]_03-07-11.JPG"); 


    FileInputStream imgStream = new FileInputStream(image); 

    byte [] buffer = new byte[(int) image.length()]; 

    imgStream.read(buffer); 

    //------------------------------------------------------------------- 


    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.18.1.1", 4444)); 

    //url = new URL ("https://graph.facebook.com/me/feed"); 
    url = new URL("https://graph.facebook.com/me/photos?access_token=AAACkMOZA41QEBACsafBxqVfXX54JqGLQSaE6YQ062NuTe3XUZBTdTEvy3R2H9Yr4PZA9r38JvLni7r1hYLuZCnBZAAPPH3krMMSKtIraiswZCiIZBu0nyYT"); 
    System.out.println("Before Open Connection"); 

    urlConn = (HttpURLConnection) url.openConnection(proxy); 

    urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString()); 

    urlConn.setDoOutput (true); 
    urlConn.setUseCaches (false); 
    urlConn.setRequestMethod("POST"); 

    // String content = "access_token=" + URLEncoder.encode ("AAACkMOZA41QEBAHQHUyYcMsLAewOYIe1j5dlOVOlMZBm6h9rvCQEFhmcBHg7ETHrdlrgv4sau573xMVuxIt8DzRxKFuqRqqBskDvOZA9iIkZCdPyI4Bu"); 

    String boundary = getBoundaryString(); 

    String boundaryMessage = getBoundaryMessage(boundary, "upload_field", "P1025[01]_03-07-11.JPG", "image/png"); 

    String endBoundary = "\r\n--" + boundary + "--\r\n"; 

    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 

    bos.write(boundaryMessage.getBytes()); 

    bos.write(buffer); 

    bos.write(endBoundary.getBytes()); 

    printout = new DataOutputStream (urlConn.getOutputStream()); 

    //printout.writeBytes(content); 

    printout.write(bos.toByteArray()); 

    printout.flush(); 
    printout.close(); 
    // Get response data. 



    //input = new DataInputStream (urlConn.getInputStream()); 

    if (urlConn.getResponseCode() == 400 || urlConn.getResponseCode() == 500) { 
     input = new DataInputStream (urlConn.getErrorStream()); 
    } else { 
     input = new DataInputStream (urlConn.getInputStream()); 
    } 

    String str; 
    while (null != ((str = input.readLine()))) 
    { 
     System.out.println (str); 
    } 
    input.close(); 

} 

public static String getBoundaryString() 
{ 
    return BOUNDARY; 
} 

public static String getBoundaryMessage(String boundary, String fileField, String fileName, String fileType) 
{ 
    StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n"); 
    res.append("Content-Disposition: form-data; name=\"").append(fileField).append("\"; filename=\"").append(fileName).append("\"\r\n") 
     .append("Content-Type: ").append(fileType).append("\r\n\r\n"); 

    return res.toString(); 
} 
} 
+0

해결책을 설명하지 않은 downvote. 소스 코드는 좋지만 리크 (Reak) 응답이 아닙니다. –

+0

코드가 다음과 같이 차용 된 것 같습니다 : http://www.thoughtwavesoft.com/cms/index.php?option=com_easyblog&view=entry&id=5&Itemid=102 소스를 언급해야합니다. 대답. – rahulserver

+0

이 솔루션을 사용하고 있지만 'Connection timed out : connect'이라고 말합니다. 도움을 청하십시오 –

0

당신은 기본 앨범

http://code.google.com/p/socialauth/

최신 릴리스 버전 3.0에이 기능이에 FB에 이미지를 업로드하기 위해 다음과 같은 API를 사용할 수 있습니다

는 솔루션입니다.

관련 문제