I am trying to use the Graph API to post on a Facebook Page, I got the access tokens and gave all the permissions needed such as public-actions and others and retrieved my page ID as well. My code seems to be working fine but my message does not get posted on the Facebook page wall. I have tried the same method with (me/feed) and it does post on my wall. However, when I post on my Facebook Page with /{page-id}/feed it doesn't work. Please help me. Here is my code:
post_on_page.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
post_on_page.setVisibility(View.VISIBLE);
Bundle params = new Bundle();
params.putString("name", "Test Name");
params.putString("message", "This is a test message");
params.putString("link", "https://www.facebook.com/Integration-test-1768******9580/");
params.putString("display", "page");
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"17680******39580/feed",
params,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Toast.makeText(getApplicationContext(),"Posted on wall",Toast.LENGTH_SHORT).show();
}
}
).executeAsync();
}
});
I have tried the same method with (me/feed) and it does post on my wall
That´s a clear indication of using the wrong Access Token. You are using a User Token, but you need to use a Page Token with the manage_pages and publish_pages permissions.
More information about Tokens and how to generate them:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
Related
I am developing an app in Android Studio (Java) that uses the Google speech recognition API and a certain other API that I am trying to make a POST request to. Here is an excerpt of my code.
String url = MY_URL;
String jsonSpeechResults = "{\"prompt\": \"" + speechResults + "\"}";
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(jsonSpeechResults, MediaType.parse("application/json"));
Request request = new Request.Builder().url(url).addHeader("Authorization", API_KEY).post(body).build();
try {
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
try {
String theResponse = response.body().string();
errorView.setText(theResponse);
} catch(Exception f) {
errorView.setText(f.getMessage());
}
}
});
} catch (Exception g) {
errorView.setText(g.getMessage());
}
Here is how this part of the app is supposed to work. When I speak some words, the speech recognition API picks up my words, and when the speech recognition results are returned, those results get sent to my other API (the one that corresponds to MY_URL) in a POST request, and then that API should return some JSON, which is then supposed to print out in string format in the errorView TextView field. If it is not apparent by this explanation, this excerpt of code is inside of the onResults method of a RecognitionListener object that is defined in the onCreate method.
Whenever I run this on my Android phone, I am expecting the response results to appear in my errorView TextView field, but instead all that appears is a single "{". Furthermore, the request doesn't even seem to get made at all the first time I speak into the phone. I have to speak again for the request to even get made (even though I know for certain that the speech recognition does work the first time; it is just the other API that doesn't seem to receive my request the first time I speak).
I don't understand why, and this is annoying me. Furthermore, I can't use
client.newCall(request).execute()
because this just returns an exception. Even the message from a try catch does not tell me what the problem is.
Can someone please help me?
i am trying to send json using postman to Lavavel but i facing this error.
enter image description here
this is my json code:
{
"email":"test#test.com",
"password":"testtest"
}
and this is Laravel codes :
Route::get('/r','test#store');
and
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Log;
class test extends Controller
{
public function store(Request $request)
{
$email = $request->input('email');
$password = $request->input('password');
Log::info('test');
Log::info($email);
Log::info($password);
DB::table('login')->insert([
['email' => $email],
['password' => $password]
]);
}
}
also i trying using android for send data using volley and so checked Laravel logs :
Column 'email' cannot be null (this is Laravel logs)
and on android Logs:
E/Volley: [299] BasicNetwork.performRequest: Unexpected response code 500 for http://192.168.1.4:8000/r
D/error: com.android.volley.ServerErro
my android code is :
public class ApiService {
private final Context context;
public ApiService(Context context){
this.context=context;
}
public void loginUser(String email, String password, final OnLoginResponse onLoginResponse){
JSONObject requestJsonObject=new JSONObject();
try {
requestJsonObject.put("email",email);
requestJsonObject.put("password",password);
JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, "http://192.168.1.4:8000/r",requestJsonObject , new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("response",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
}) {
#Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
return headers;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(18000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(context).add(request);
} catch (JSONException e) {
Log.e(TAG, "loginUser: "+e.toString());
}
}
public interface OnLoginResponse{
void onResponse(boolean success);
}
}
I hope this helps people trying to search on how to send JSON data to laravel not only specific to android applications but to all. The goal of this solution is to identify whether you can send a JSON data to laravel or not.
First of all you have to download postman from https://www.getpostman.com/ to test if your API is really working or not.
Create a post request using postman. Be sure that you follow the example data below
Be sure that you set your Routes that would associate to the controller
This is the controller part that will show the JSON data you sent if it was successfully accepted or not.
And also, if ever you are trying to send POST data to laravel, by default they provided a CSRF Token which is applicable for the forms if you are going to use the MVC of laravel. For the meantime, we are going to take this down and comment it out. Just go to app/http/kernel.php
and now you'll get the following result from the code earlier
$json = json_decode($request['json']);
echo $json->{'email'};
echo "\n";
echo $json->{'password'};
We tested that we were able to send data to laravel. I hope this truly helps.
Wen you want to send data, you will want to use POST or PUT method on your postman, specially if you are sending a body, that means that you are sending data. Get method is used to retrieve data from a service.
Take a look into CRUD functions for more information.
Your postman should look something like this
Last in your android code try to change this line
JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, "http://192.168.1.4:8000/r",requestJsonObject , new Response.Listener<JSONObject>() {
to use Request.Method.POST
Background:
I'm working on an Android project that was handed off to me and there are some things I'm still trying to learn. The people on the project before me left no documentation, so forgive me.
Question:
Basically I want to know how to get data back from our MongoDB (I think). Using AsyncHttpClient params are put sent via post
private AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("authorization", getSharedPreferences("Prefs", Context.MODE_PRIVATE).getString("authToken", ""));
params.put("name", name);
params.put("email", email);
client.post(Utilities.getBaseURL() + "session/updateProfile", params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) {
HashMap<String, String> profile = new HashMap<>();
profile.put("user_name", name);
profile.put("user_email", email);
Utilities.updateAllDetails(profile);
}
#Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, Throwable throwable, JSONObject response) {
Utilities.showUserDialog(context, "Profile Change Error", "Attention, there was an error in updating your profile, please try again.");
}
});
So the above code is basically updating a profile and sending the params via http post.
Later there is a get on the client:
client.get(Utilities.getBaseURL() + "session/getUserId", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) {
try {
userId = response.getString("responseString");
startActivityForResult(intent, PICK_IMAGE);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, Throwable throwable, JSONObject response) {}
});
What I don't understand is where "session/updateProfile" and "session/getUserId" come from. Is this an API call, if so how can I find what is available and also how to add to it?
Update
Found this code in a JavaScript file for the website. Maybe this can lead someone to help me put everything together?
JsonRoutes.add('get', '/api/v1/session/getUserId', function(req, res, next) {
var authToken = req.headers["authorization"];
var userObj = verifyUser(authToken);
var response = {};
if (userObj) {
response.responseString = userObj._id;
JsonRoutes.sendResult(res, 200, response);
} else {
response.responseString = "user not found";
JsonRoutes.sendResult(res, 200, response);
}
});
Do I need to add to this JS file to expand the API?
where [do] "session/updateProfile" and "session/getUserId" come from? Is this an API call
Yup, REST API call to wherever Utilities.getBaseURL() points to.
how can I find what is available?
Well, if that server is yours, then you'll need to go find some code / documentation for that. Otherwise, if it's some other external service, you'll still have to find some API documentation or contact someone who does know about it. You've mentioned in the comments that it is DigitalOcean, so it isn't an external service. There is additional server side code to inspect.
how to add to it?
If it were an external service, you probably couldn't. Since this DigitalOcean server could be running literally any service, it entirely depends on the server side programming language. You've mentioned that Javascript file along with MongoDB, so I'm guessing it's some NodeJS variant. You mention MeteorJS in the comments, so that's the documentation you need to add new features.
Do I need to add to this JS file to expand the API?
Simply: yes.
I want to know how to get data back from our MongoDB
Essentially this line is doing that. Of course, the response code shouldn't always be 200 and the content of the response string can be anything you want, but probably should be JSON, or at least something Android can parse
JsonRoutes.sendResult(res, 200, response);
im trying to get the users group list.
before i ask how to extract that information from the "response" this is my code:
permissions:
this.login = (LoginButton)findViewById(R.id.login_button);
login.setReadPermissions(Arrays.asList("user_groups", "friends_groups"));
request:
Request share = Request.newGraphPathRequest(session, "/me/groups", new Request.Callback() {
#Override
public void onCompleted(Response response) {
GraphObject go = response.getGraphObject();
Log.d("getting groups", go.toString());
}
});
first of all a few issues:
1. the log.d line not showing. meaning the app dosent get to that call back.
is the code ok?
how to handle the response, meaning how to extract the information?
thank you !
Hi I'm using Scribe to Send a LinkedIn invite, but I'm a little unsure how to use it. I've created the XML body as a string with all the neccessary values inserted but when I make the API call the invite isn't sent. My code is as follows
invite.setOnClickListener(new Button.OnClickListener()
{
public void onClick (View v)
{
inviteXml = inviteCreator.inviteString(to, subj, body, authName, authValue);
titleField.setText("");
call = "http://api.linkedin.com/v1/people/~/mailbox";
request = new OAuthRequest(Verb.POST, call);
//request.addPayload(inviteXml);
request.addBodyParameter("body", inviteXml);
service.signRequest(accessToken, request);
response = request.send();
nameField.setText(response.getBody());
invite.setVisibility(View.GONE);
}
});
on the line request.addPayload(inviteXml); this causes the app to crash. The line request.addBodyParameter("body", inviteXml); returns an error xml message that has a status of 400 with an error code 0 and tht message "Couldn't parse mailbox-item document: error:Unexpected end of file after null"
Am I going about this the wrong way or have I missed something inportant? I've read the LinkedIn documentation but it doesn't seem to say how to add the xml message to the appi call.
Thanks for any help
Jeff
Have you tried to specify Content-Lenght and Content-Type ?
Something like this:
request.addHeader("Content-Length", Integer.toString(inviteXml.length())); request.addHeader("Content-Type", "text/xml");
request.addPayload(inviteXml);