Facebookページで公開された投稿を認証なしでアプリに表示したい。コードは次のとおりです。
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
String APP_ID = "1234567890";
String APP_SECRET = "1a2b3c4defghijk";
String OWNER_OF_FEED = "somepage";
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(
"https://graph.facebook.com/oauth/access_token?client_id="+
APP_ID +
"&client_secret="+APP_SECRET+"&grant_type=client_credentials");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String access_token = client.execute(get, responseHandler);
String uri = "https://graph.facebook.com/" + OWNER_OF_FEED + "/feed?"
+ access_token;
get = new HttpGet(uri);
String responseBody = client.execute(get, responseHandler);
// responseBody contains JSON-encoded feed
//textview.setText(responseBody);
TextView txtv = (TextView) findViewById(R.id.feed);
txtv.setText(String.valueOf(responseBody));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
ただし、アプリでコンテンツを取得できません。マニフェストファイルにインターネットアクセスの許可を含めました。
新しいコード:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
URL url;
try {
url = new URL("https://www.facebook.com/feeds/page.php?format=rss20&id=289781571139242");
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}