0

Facebookアプリの開発は初めてで、ユーザーの壁に簡単なメッセージを投稿しようとしています。アクセストークンを取得できました。POSTリクエストのコードは次のとおりです。Javaサーブレットを使用しています。

  String data = URLEncoder.encode("access_token", "UTF-8") + "=" + URLEncoder.encode(accessToken, "UTF-8");
data += "&" + URLEncoder.encode("message", "UTF-8") + "=" + URLEncoder.encode("finally", "UTF-8");
out.println("data is\n"+data);
// Send data
String u="https://graph.facebook.com/me/feed";
URL urls = new URL(u);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();

さて、このコードは機能しておらず、壁に投稿することはできません。どこが間違っている可能性があるかについての提案はありますか?

4

1 に答える 1

0

application/x-www-form-urlencodedコンテンツタイプを指定していないためだと確信しています。これを試してください。

URLConnection connection = new URL("https://graph.facebook.com/me/feed").openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(data);
out.flush();
out.close()

編集

さて、この問題を引き起こす可能性のあるものがさらに2つあります。

  1. コンテンツの長さも指定する必要があります。
  2. あなたはそれを数えるために応答を読む必要があるかもしれません。

このコードはテストされ、機能します。

StringBuffer buffer = new StringBuffer();
buffer.append("access_token").append('=').append(ACCESS_TOKEN);
buffer.append('&').append("message=").append('=').append("YO!");
String content = buffer.toString();

URLConnection connection = new URL("https://graph.facebook.com/me/feed").openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(content.length()));

DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(content);
out.flush();
out.close();

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) { 
    System.out.println(inputLine);
}

in.close();
于 2012-06-06T12:17:38.143 に答える