如何从Servlet中使用Facebook的Graph-API [英] How to use Facebooks Graph-API from a Servlet

查看:227
本文介绍了如何从Servlet中使用Facebook的Graph-API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从J2EE-App(服务器端)访问Facebook。
我第一次看这个项目: http:// code。 google.com/p/facebook-java-api/
,但是因为我需要创建Facebook - 活动,并邀请人们无助于。

I need to access Facebook from a J2EE-App (serverside). I first had a look at this project: http://code.google.com/p/facebook-java-api/ , but as I need to create Facebook-Events and invite people this does not help.

所以我想我需要使用Graph API,但是没有关于如何执行这些HTTP POST请求的线索,特别是如何附加nedded属性。

So I guess I need to use the Graph API, but Igot no clue on how to perform those HTTP POST requests needed - especially how to append the nedded attributes.

推荐答案

您可以使用

You can use the java.net.URLConnection for this:

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

Alternatively, you can also use the more convenienced HttpClient API for this:

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.

这篇关于如何从Servlet中使用Facebook的Graph-API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆