我需要从 J2EE 应用程序(服务器端)访问 Facebook。
我首先看了一下这个项目:http://code.google.com/p/facebook-java-api/ http://code.google.com/p/facebook-java-api/,但由于我需要创建 Facebook 活动并邀请人们,这没有帮助。
所以我想我需要使用 Graph API,但我不知道如何执行所需的 HTTP POST 请求 - 特别是如何附加所需的属性。
您可以使用java.net.URLConnection http://java.sun.com/javase/6/docs/api/java/net/URLConnection.html为了这:
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¶m2=%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.
或者,您还可以使用更方便的Http客户端API http://hc.apache.org/httpcomponents-client/index.html为了这:
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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)