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

本文详细介绍了如何使用URLEncoder进行特殊字符转码,并通过HTTP POST请求与HttpClient API发送参数到Facebook API,包括编码、设置请求头和执行请求的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

特殊字符转码: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. 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值