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/
Related
I have the following json structure which i need to send it to server using post request. Please help in making the same structure by code in android.
The json structure is as follows :
{
"
}
}
Since i am newbie to android so please help.
Use the JSONObject class in android, here is an example:
JSONObject object = new JSONObject();
JSONObject cardAcceptorkey = new JSONObject();
try {
//CREATE cardAcceptorkey object
cardAcceptorkey.put("id","CA-IDCode");
cardAcceptorkey.put("name","USA");
...
//CREATE object
object.put("AuditNumber", "451035adss");
object.put("cardAcceptorkey", cardAcceptorkey);
...
} catch (JSONException e) {
e.printStackTrace();
}
More info: http://www.vogella.com/tutorials/AndroidJSON/article.html
I'm trying to setup a survey that my app users can take that will post the results to a rails app. The survey/questions/answers are built in the rails app, then displayed in the Android app. After the user answers each question it should post back to the server.
I suspect that it's something to do with my create method (the uncommented line works for creating a choice in the rails app but not for the Android post and the commented line appears to work for neither) but I'm relatively new to Android/Rails so any help would be much appreciated!
Here's my ChoicesController:
class ChoicesController < ApplicationController
# POST /choices
# POST /choices.json
def create
#question = Question.find(params[:question_id])
#choice = #question.choices.build(choice_params)
#choice.answer = Answer.find(params[:choice][:answer_id])
# #choice.answer = Answer.find(params[:answer_id])
respond_to do |format|
if #choice.save
format.html { redirect_to question_choices_path, notice: 'Choice was successfully created.' }
format.json { render action: 'show', status: :created, location: #choice }
else
format.html { render action: 'new' }
format.json { render json: #choice.errors, status: :unprocessable_entity }
end
end
end
My choice model:
class Choice < ActiveRecord::Base
belongs_to :question
belongs_to :answer
belongs_to :user
validates :question_id, presence: true
validates :answer_id, presence: true
end
Here's how I'm creating/posting my json in Android:
public boolean postChoice(String apiKey) {
boolean choicePosted = false;
try {
post();
} catch (Exception e) {
e.printStackTrace();
}
choicePosted = true;
return choicePosted;
}
public static void post() {
Map<String, String> choice = new HashMap<String, String>();
choice.put("question_id", "6");
choice.put("answer_id", "15");
String json = new GsonBuilder().create().toJson(choice, Map.class);
makeRequest("http://localhost:3000/choices/", json);
}
public static HttpResponse makeRequest(String uri, String json) {
try {
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(json));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
return new DefaultHttpClient().execute(httpPost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Any help is much appreciated!
One big problem with your code is:
} catch (Exception e) {
e.printStackTrace();
}
You are swallowing all exceptions and my guess you are also swallowing the problem exception. You should look into logs what exception is recorded and also not use catch (Exception e) but instead have explicit exception.
Without actual exception it hard to diagnose, but my guess is that you are making this http request inside UI thread and Android framework explicitly forbids it (it makes your app non-responsive) and throws an exception.
Turns out the biggest problem I had was that I was not sending a CSRF token with my POST. including skip_before_action :verify_authenticity_token solved my problem. Since it's an API I have a few other security verification piece in place, but CSRF really only applies to web forms anyway.
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
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 have written a web application to run on Google AppEngine using the Restlet framework, communicating using json with web clients. Those work as expected. However, one specific resource written to provide response to an Android client doesn't work when accessed through Android. However, it does work when accessed through a web browser (I do not send the request parameters from the browser and thus get a 400 which is ok in this case).
This code works when running on the DevAppServer:
public class PlayResource extends ServerResource {
private final float SCOREBASE = 1000.0F;
#Get
#Post
public JsonRepresentation play() {
try {
JsonRepresentation rep = new JsonRepresentation(getRequestEntity());
JSONObject inputJson = rep.getJsonObject();
JSONObject outputJson = new JSONObject();
String country = inputJson.optString("country");
outputJson.put("country", doSomething("country",country));
......
......
return new JsonRepresentation(outputJson);
} catch (IOException e) {
try {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return new JsonRepresentation(
new JSONObject()
.put(Messages.TYPE_ERROR, Messages.BAD_REQUEST));
} catch (JSONException e2) {
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
} catch (JSONException e) {
try {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return new JsonRepresentation(
new JSONObject()
.put(Messages.TYPE_ERROR, Messages.BAD_FORMAT));
} catch (JSONException e2) {
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
}
}
}
and the client Android device is running this code:
Client client = new Client(Protocol.HTTP);
try {
JsonRepresentation requestJSON = new JsonRepresentation(new JSONObject()
.put("country", country.trim())
);
Request req = new Request(Method.GET,"http://****.appspot.com/resource/play",requestJSON);
Response resp = client.handle(req);
String res = resp.getEntity().getText();
JSONObject resultJSON = new JSONObject(res);
Running this request just hangs the Android client, the server doesn't write any log messages whatsoever suggesting the request doesn't arrive there.
It seems that it's more a Appengine/Java issue than an android issue, but...let's try something else:
instead of using Client and the stuff u are using, first just try to see what the server responds to the simplest connection (as you do in a web browser):
URL url;
try {
url = new URL("http://yourappid.appspot.com/resource/play");
String content = (String) url.getContent();
System.out.println(content);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If it works and you get your expeted 400, if so...try to send an httppostrequest with the data...like this:
HttpClient client = new DefaultHttpClient();
HttpUriRequest httpRequest = new HttpPost("http://yourappid.appspot.com/resource/play");
//set the content type to json
httpRequest.setHeader("Content-Type", "application/json");
//get and work with the response
HttpResponse httpResponse = client.execute(httpRequest);
Let me know if the answer was useful