2

我需要从 J2EE-App(服务器端)访问 Facebook。我首先看了一下这个项目:http ://code.google.com/p/facebook-java-api/ ,但是因为我需要创建 Facebook-Events 并邀请人们,所以这无济于事。

所以我想我需要使用 Graph API,但我不知道如何执行所需的那些 HTTP POST 请求——尤其是如何附加 nedded 属性。

4

1 回答 1

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

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.
于 2010-04-29T15:56:51.100 回答