First, I can log in my facebook and I already save access token in SharedPreferences.
However, when I try to this code:
JSONObject json_data = null;
try
{
JSONObject response = Util.parseJson(new Facebook(Define.APP_ID).request("me/friends"));
JSONArray jArray = response.getJSONArray("data");
json_data = jArray.getJSONObject(0);
String name = json_data.getString("name");
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (FacebookError e)
{
e.printStackTrace();
}
I got an error "An active access token must be used to query information about the current user".
What should I do? I have access token already.
Isn't it better to use Facebook SDK for Android 3.0 which handles almost everything for you. There is method executeMyFriendsRequestAsync(Session session, Request.GraphUserListCallback callback) from Request class which returns list of your friends in callback. Here is getting started guide: https://developers.facebook.com/docs/getting-started/facebook-sdk-for-android/3.0 . If you use the sample code from this guide and change the type of request which is executed you will get the same information you're trying to get in code you provided.
You shoudn't do any request from Facebook Object directly. You have to create Facebook Object first and then set the AccessToken, Expiry Time and then do the requests as below.
FaceBook fb = new FaceBook(APP_ID);
fb.setAccessToken("youraccesstoken");
fb.setAccessExpires(expires);//expires is your milliseconds time.
Then you do your requests as fb.request("me/friends");
Your are requesting the information without a valid authenticated Session. So you are getting that error. Do authentication and set the access token then you get no problem
Related
I'm trying to copy url contents with user info.
First, the user log in and then the page show the user info. I want to copy that info to a String.
I am using this:
try {
variable1 = new Scanner(new URL("https://example.com/hello").openStream(), "UTF-8").useDelimiter("\\A").next();
}catch (MalformedURLException e) {
System.out.println("The URL is not valid.");
}catch (IOException e) {
System.out.println("The URL is not valid.");
}
But I am getting the content in the login page...(as the user never logged in).
I thing maybe missing the cookie id in the request header. The cookie id is in the header of the response after the login request finished.
I am new to Facebook API. Trying the FQL Query from the Graph API for the first time using this link.
I am trying to get photos from the album with the album id. When I request using Facebook object with https://graph.facebook.com/10150146071791729/photos&access_token=ACCESS_TOKEN URL, I am getting the following response (before parsing to JSON object). {"id":"https://graph.facebook.com/10150146071791729/photos","shares":2}. And I confirmed it by printing the length of the JSON object after parsing, which is 2. When I copy and paste the same URL in the web browser, I am getting the expected response (the response in FQL Query I got). Here is my code.
public void onComplete(Bundle values) {
String token = facebook.getAccessToken();
System.out.println("Token: " + token);
try {
String response = facebook.request("https://graph.facebook.com/10150146071791729/photos&access_token=ACCESS_TOKEN");
System.out.println("response :"+response);
JSONObject obj = Util.parseJson(response);
System.out.println("obj length : " + obj.length());
Iterator iterator = obj.keys();
while(iterator.hasNext()){
String s = (String)iterator.next();
System.out.println(""+s+" : "+obj.getString(s));
}
} catch (Throwable e) {
e.printStackTrace();
}
}
Note: I got access token from the FQL Query which is used in the URL. And I did not wrote any session (login/logout) logic as it is a test project.
Your request is wrong. It should be
"https://graph.facebook.com/10150146071791729/photos?access_token=ACCESS_TOKEN"
Replace the '&' after the photos with a '?'.
Two more things, you're making a Graph API query, not an FQL one.
Second, NEVER post your access tokens publicly. If I wanted to, I can now use your access token to edit your facebook information.
EDIT: When you use the Android Facebook SDK, you do not need to use the full graph path. Instead, use
facebook.request("10150146071791729/photos")
You do not need to add the access token as the Facebook object already has it. Hope this helps.
Because not much code has been provided except for the most relevant one, let me give you a couple of ways you can access Photos from an Album
FIRST METHOD (IF your wish to use the complete URL to make the request)
String URL = "https://graph.facebook.com/" + YOUR_ALBUM_ID
+ "/photos&access_token="
+ Utility.mFacebook.getAccessToken() + "?limit=10";
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet(URL);
HttpResponse rp = hc.execute(get);
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String queryPhotos = EntityUtils.toString(rp.getEntity());
Log.e("PHOTOS RESULT", queryPhotos);
}
} catch (Exception e) {
e.printStackTrace();
}
SECOND METHOD (Without using the complete URL as #Vinay Shenoy mentioned earlier)
try {
Bundle paramUserInfo = new Bundle();
paramUserInfo.putString(Facebook.TOKEN, Utility.mFacebook.getAccessToken());
String resultPhotos = Utility.mFacebook.request("YOUR_ALBUM_ID/photos", paramUserInfo, "GET");
Log.e("PHOTOS", resultPhotos);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
On a personal note, I follow the first method almost entirely through my application. It lets me using the Paging for endless ListViews
That being said, when I need some quick data in between somewhere, I do rely on the second method. Both of them work and I hope either (or both) of them helps you.
I want to pasrse the json login Api..where the login page contains Pinnumber and password.
.. i want to login with these details and then want to go to registration page.. with the details from the Api.. can anyone help me in this
thanks in advance
Please try this code below:
String response ="{\"0\":{\"SessionId\":\"zDQKMvGMWD4e9960e376988\"},\"memberdetails\":{\"Ident\":8,\"PinNumber\":\"justpinme1\",\"Password\":\"justpinme1\",\"EmailAddress\":\"justpinme1#gmail.com\",\"FirstName\":\"test1\",\"LastName\":123,\"Birthdate\":19860909,\"Gender\":\"female\",\"Country\":\"india\",\"PhoneNumber\":2147483647,\"PhotoThumb\":\"\",\"PhotoOriginal\":\"\",\"RegisteredDate\":\"2011-09-06 09:18:31\",\"RegisteredIp\":\"122.165.76.30\",\"RegisteredDeviceId\":22,\"LastSessionId\":\"hbS4JV9DNv4e99600c38390\",\"Status\":\"Active\",\"SessionId\":\"zDQKMvGMWD4e9960e376988\"}}";//Assign the response that are getting on the login api
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject forSessionId = jsonObject.getJSONObject("0");
String SessionId = forSessionId.getString("SessionId");
System.out.println("SessionId="+SessionId);
JSONObject memberdetails = jsonObject.getJSONObject("memberdetails");
System.out.println("Ident="+memberdetails.getString("Ident"));
System.out.println("PinNumber="+memberdetails.getString("PinNumber"));
System.out.println("Password="+memberdetails.getString("Password"));
System.out.println("EmailAddress="+memberdetails.getString("EmailAddress"));
System.out.println("FirstName="+memberdetails.getString("FirstName"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am trying to use graph batch api , is there any reference code ? how do we set the
parameters ? Has anyone used batch api with reference to android apps
I am using this link
and I've also have used individual graph apis such as
fbApiObj.request("me/notifications");
fbApiObj.request("me/home");fbApiObj.request("me/friends");
I want to batch them. The explanation provided in the link above is not very clear as to how to convert to api calls.
What you need to do is build a JSONArray for your request, and then convert that JSONArray to a string before you send it to the server using HTTPS POST. For each request, make a JSONObject according to the Facebook API (link previously posted), then add all these JSONObjects to a JSONArray and use the Facebook SDK's built-in "openUrl" method (located in the Util class inside the SDK).
Here's a small example that I built for testing the batch.
JSONObject me_notifications = new JSONObject();
try {
me_notifications.put("method", "GET");
me_notifications.put("relative_url", "me/notifications");
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
}
JSONObject me_home = new JSONObject();
try {
me_home.put("method", "GET");
me_home.put("relative_url", "me/home");
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
}
JSONObject me_friends = new JSONObject();
try {
me_friends.put("method", "GET");
me_friends.put("relative_url", "me/friends");
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
}
JSONArray batch_array = new JSONArray();
batch_array.put(me_home);
batch_array.put(me_notifications);
batch_array.put(me_friends);
new FacebookBatchWorker(this, mHandler, false).execute(batch_array);
And the FacebookBatchWorker is simply an asynctask (just use any threading you want really...). The important part is the HTTPS request, I used the already available ones inside the facebook SDK, like this.
The "params[0].toString()" is the JSONArray I sent to the AsyncTask, we need that converted to a String for the actual post request.
/* URL */
String url = GRAPH_BASE_URL;
/* Arguments */
Bundle args = new Bundle();
args.putString("access_token", FacebookHelper.getFacebook().getAccessToken());
args.putString("batch", params[0].toString());
String ret = "";
try {
ret = Util.openUrl(url, "POST", args);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Hopefully you'll get something out of this...
The batch requests from the facebook graph API are available through HTTP requests. It does not matter whether the request comes from an android phone or not.
It is a quite recent feature and the facebook android sdk has not been updated recently in github, so you will need to handle those requests directly.
Reference: http://developers.facebook.com/docs/reference/api/batch/
Anybody can please help in Android + Twitter Integration using OAuth.
I already worked on http://github.com/brione/Brion-Learns-OAuth and getting the error listed below, when I am posting status update...
WARN/System.err(190): org.apache.http.client.HttpResponseException: Unauthorized
WARN/System.err(190): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:71)
WARN/System.err(190): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:59)
WARN/System.err(190): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:657)
WARN/System.err(190): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)
WARN/System.err(190): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
WARN/System.err(190): at com.test.twitter.BLOA$PostTask.doInBackground(BLOA.java:343)
WARN/System.err(190): at com.test.twitter.BLOA$PostTask.doInBackground(BLOA.java:1)
WARN/System.err(190): at android.os.AsyncTask$2.call(AsyncTask.java:185)
WARN/System.err(190): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:256)
WARN/System.err(190): at java.util.concurrent.FutureTask.run(FutureTask.java:122)
WARN/System.err(190): at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:648)
WARN/System.err(190): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:673)
WARN/System.err(190): at java.lang.Thread.run(Thread.java:1060)
I succeed with OAuth Authentication and getting user_secret and user_token and stored in preferences...
So the issue is with http posting using OAuth header...
and My Http Post Method is as :
private class PostTask extends AsyncTask<String, Void, JSONObject> {
ProgressDialog postDialog;
#Override
protected void onPreExecute() {
postDialog = ProgressDialog.show(BLOA.this,
getText(R.string.tweet_progress_title),
getText(R.string.tweet_progress_text), true, // indeterminate
// duration
false); // not cancel-able
}
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jso = null;
try {
HttpPost post = new HttpPost(
"http://twitter.com/statuses/update.json");
LinkedList<BasicNameValuePair> out = new LinkedList<BasicNameValuePair>();
out.add(new BasicNameValuePair("status", params[0]));
post.setEntity(new UrlEncodedFormEntity(out, HTTP.UTF_8));
post.setParams(getParams());
// sign the request to authenticate
mConsumer.sign(post);
String response = mClient.execute(post,
new BasicResponseHandler());
jso = new JSONObject(response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
return jso;
}
// This is in the UI thread, so we can mess with the UI
protected void onPostExecute(JSONObject jso) {
postDialog.dismiss();
if (jso != null) { // authorization succeeded, the json object
// contains the user information
mEditor.setText("");
mLast.setText(getCurrentTweet(jso));
} else {
mLast.setText(getText(R.string.tweet_error));
}
}
}
Although you are received the user_secret and user_token successfully in onResume(), are you sure your original objects are still the same? I had this problem in my Android app. I would create the objects, but when onResume() was called it was a totally new instance of the Activity because it was free'd from memory when the browser launched. So when I tried to set the returned secret/token pair it wouldn't work. This is more likely to happen on a device with limited memory. Some people choose to persist the necessary info between calls and others decide to not launch the default browser intent, but rather host an embedded webview so their original signpost-oauth objects don't go out of scope.
OAuth instance state in Android
Not sure if this is the issue, but maybe worth a look.
You need to add the oauth information to the headers of the http request using post.addHeader(). To know which things to add to the headers, take a look here: http://dev.twitter.com/pages/auth
Please describe what Client/Consumer/Provider you are using, they must be DefaultHttpClient/CommonsHttpOAuthConsumer/CommonsHttpOAuthProvider to work properly for sure.
Ensure you call consumer.setTokenWithSecret(oToken, oTokenSecret); before calling this code.
Also, is post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); exists in your post params?
What's the reason for using empty BasicResponseHandler, it handles nothing and it can be omitted in execute call, I suppose.
And, may be a dumb question, may be you are overwriting params when calling setParams(...) after setEntity(...)
I have 2 tutorials for 2 different Java libs. First one (dated) is here, and 2nd one here with Scribe. It's for LinkedIn but it would be very easy to switch to Twitter. I would go with #2