首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

从Servlet使用Facebooks Graph-API以及编码有关问题

2012-09-19 
从Servlet使用Facebooks Graph-API以及编码问题特殊字符转码:String param URLEncoder.encode(Hermann-

从Servlet使用Facebooks Graph-API以及编码问题

特殊字符转码:String param = URLEncoder.encode("Hermann-L?ns", "UTF-8");

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.?

热点排行