2010-04-29 5 views
2

J2EE-App (서버 측)에서 Facebook에 액세스해야합니다. 먼저이 프로젝트를 살펴 보았습니다 : http://code.google.com/p/facebook-java-api/ ,하지만 페이스 북 이벤트를 생성하고 사람들을 초대해야하므로 도움이되지 않습니다.서블릿에서 Facebook-Graph-API를 사용하는 방법

그래서 그래프 API를 사용해야 할 필요는 없지만 필요한 HTTP POST 요청을 수행하는 방법에 대한 단서는 없습니다. 특히 내장 속성을 추가하는 방법은 특히 필요하지 않습니다.

답변

2

이에 대한 java.net.URLConnection를 사용할 수 있습니다

String url = "http://facebook.com/some/api"; 
String charset = "UTF-8"; 
String param1 = URLEncoder.encode("value1", charset); 
String param2 = URLEncoder.encode("value2", charset); 
String query = String.format("param1=%s&param2=%s", param1, param2); 

URLConnection urlConnection = new URL(url).openConnection(); 
urlConnection.setUseCaches(false); 
urlConnection.setDoOutput(true); // Triggers POST. 
urlConnection.setRequestProperty("accept-charset", charset); 
urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 

OutputStreamWriter writer = null; 
try { 
    writer = new OutputStreamWriter(urlConnection.getOutputStream(), charset); 
    writer.write(query); // Write POST query string (if any needed). 
} finally { 
    if (writer != null) try { writer.close(); } catch (IOException logOrIgnore) {} 
} 

InputStream response = urlConnection.getInputStream(); 
// Now do your thing with the facebook response. 

또는, 당신은이에 대한 HttpClient API 더 convenienced를 사용할 수 있습니다

String url = "http://facebook.com/some/api"; 
String charset = "UTF-8"; 
List<NameValuePair> params = new ArrayList<NameValuePair>(); 
params.add(new BasicNameValuePair("param1", "value1")); 
params.add(new BasicNameValuePair("param2", "value2")); 
UrlEncodedFormEntity query = new UrlEncodedFormEntity(params, charset); 

HttpClient client = new DefaultHttpClient() 
HttpPost post = new HttpPost(url); 
post.setEntity(query); 
InputStream response = client.execute(post).getEntity().getContent(); 
// Now do your thing with the facebook response. 
+0

덕분에 많이! 방금 ​​시작한 http://restfb.com/을 사용하기 시작했습니다. – Eric

관련 문제