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);
Related
We are unable to subscribe web-hook for SharePoint online from our Spring-Boot application.
Providing valid notification URL(https enabled, publicly accessible, valid domain name, Post method) as parameter while consuming rest API in order to subscribe web-hook.
#PostMapping(value = "/spnotification")
#ResponseBody
public ResponseEntity<String> handleSPValidation(#RequestParam final String validationtoken) {
LOG.info("validationToken : " + validationtoken);
return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN)
.body(validationtoken);
}
And on this notification URL end-point, we are able to receive validation string from share-point as parameter and same string we are retiring in less then 5 sec with content-type text/plain and http status code 200 as response.
still getting 400 bad request with below error message.
400 Bad Request: [{"error":{"code":"-1, System.InvalidOperationException","message":{"lang":"en-US","value":"Failed to validate the notification URL 'https://example.com/notification-listener-service/api/webhook/spnotification'."}}}]
Note : We are following this API documentation to subscribe web-hook.
We tried Graph API also for the same purpose but in that case getting below error.
"error": {
"code": "InvalidRequest",
"message": "The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF"
}
Please find this diagram for more understanding on this issue.
We really appreciate if someone can help us on the same.
Please check the #PostMapping(value = "/notification", headers = { "content-type=text/plain" })
#PostMapping(value = "/notification", headers = { "content-type=text/plain" })
#ResponseBody
public ResponseEntity<String> handleSPValidation(#RequestParam final String validationtoken) {
LOG.info("validationToken : " + validationtoken);
return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN)
.body(validationtoken);
}
GitHub Code
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
I'm trying to communicate with Instagram's API but the reply I get back from my request says that the parameters I passed onto the body weren't detected.
{"error_type":"OAuthException","code":400,"error_message":"You must provide a client_id"}
I tried to send the request by passing a JsonNode or a string inside .post(), like below, but both where unsuccessful.
public CompletionStage<Result> getInstagramToken() {
String code = request().getQueryString("code");
if(code != null) {
WSRequest request = ws.url("https://api.instagram.com/oauth/access_token").setContentType("application/x-wwww-form-urlencoded");
// Json body
/*JsonNode body = Json.newObject()
.put("client_id", insta_clientId)
.put("client_secret", insta_clientSecret)
.put("grant_type", "authorization_code")
.put("redirect_uri", redirect_uri)
.put("code", code);*/
// String body
String body = "client_id="+insta_clientId+"&client_secret="+insta_clientSecret+"&grant_type=authorization_code&redirect_uri="+redirect_uri+"&code="+code;
CompletionStage<WSResponse> response = request.post(body);
return response.thenApplyAsync(resp -> ok(resp.asJson()), exec);
}
return null;
}
The same request passed flawlessly when trying to send it by using a curl command on a terminal or with the Rested plugin on chrome ( where "content type" is set to "application/x-www-form-urlencoded" and the parameters are placed inside "Request body" )
Does anyone have any idea as to how I am supposed to send this request ?
ps: I am also looking for a way to retrieve the value received from my request and store it in a variable instead of returning it to the client.
It seems you are missing a:
.setContentType("application/x-www-form-urlencoded")
Look at our code below. In the post() you can also use a Json object so you can send a HashMap:
CompletionStage<Result> out = ws.url(cbUrl)
.setAuth(<<your user>> , <<your password>>, WSAuthScheme.BASIC)
.setRequestTimeout(Duration.ofSeconds(5))
.setContentType("application/x-www-form-urlencoded")
.post("param=value")
.handle((response, error) -> {
// Was the Chargebee API successful?
if (error == null) {
// Debugging purposes
JsonNode jn = response.asJson();
Logger.debug(Json.toJson(postMap).toString());
Logger.debug(jn.toString());
// Success stuff
return ok("good");
} else {
// Error stuff
return ok("bad");
}
});
Hope this helps you.
I've been stock for a while and seems like Google volley isn't working as I expect.
I've a JsonObject request prepared as this:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("auth-code", authCode);
} catch (JSONException ignored) {
}
JsonObjectRequest response = new JsonObjectRequest(UrlController.getGoogleOauthSendAuthCodeMethod(), UrlController.getGoogleOauthSendAuthCodeUrl(), jsonObject.toString(), onSuccess, onError);
AppController.getInstance().addToRequestQueue(response, "REGISTER_USER_GOOGLE_OAUTH");
It just sends google auth-code to my server and gets a jsonObject as response.
In response to that request I retrieve this:
{"data":{"user":
{"name":"name lastname",
"username":"someusername",
"email":"email#gmail.com"},
"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjQxNDIsImlzcyI6Imh0dHA6XC9cL2FzaG9qYXNoLm1pbFwvYXBpXC92MVwvYXV0aFwvZ29vZ2xlIiwiaWF0IjoxNDUyNDY3NTQ4LCJleHAiOjE0NTI0NzExNDgsIm5iZiI6MTQ1MjQ2NzU0OCwianRpIjoiMTNhNjU0MjcwMmQ2MmE5MDA1YTgyZTlkZTM3YjQxNGQifQ.YfQaGuhVTYXPizdt2AX8C0RAObUNoqJp4rglZPOGW7s",
"is_new_user":false
}
}
But Volley always, enters onError section.
I have tested the server api, as it returns this data.
Some note-worthy thing:
When I return this json object, without checking the auth-code and just returning a random user from the database, the code enters the onResponse callback. I've logged the server, I got auth-code there too ,and retrieving response correctly.
So what I'm doing wrong?
Found the reason, Volley time-out request is 2.5 sec.
I was authenticating an auth-code which was taking more than that time.
To solve it use this code snippet for your Volley Request
response.setRetryPolicy(new DefaultRetryPolicy(15000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
15000 is requestTimeOut in ms.
I'm trying to get user profile information by using following code. I'm using scribe to get the information. I'm able to get familyName and givenName etc. but it is not returning me the email id.
I'm using the following code:
OAuthRequest request = new OAuthRequest(
Verb.GET,
"https://social.yahooapis.com/v1/me/guid? format=xml"
);
service.signRequest(accessToken, request);
request.addHeader("realm", "yahooapis.com");
Response response = request.send();
And this is the response I got:
{
"profile": {
"guid":"CGGT5LNT7NXGFK64QW7FQN5UQM",
"ageCategory":"A",
"familyName":"gto",
"givenName":"CTSDemo",
"image": {
"height":192,
"imageUrl":"https://s.yimg.com/dh/ap/social/profile/profile_b192.png",
"size":"192x192",
"width":192
},
"intl":"us",
"jurisdiction":"us",
"lang":"en-US",
"location":"Bangalore",
"memberSince":"2014-08-03T08:23:27Z",
"nickname":"CTSDemo",
"notStored":false,
"nux":"3",
"profileMode":"PUBLIC",
"profileStatus":"ACTIVE",
"profileUrl":"http://profile.yahoo.com/CGGT5LNT7NXGFK64QW7FQN5UQM",
"updated":"2014-08-29T12:00:44Z",
"isConnected":false,
"profileHidden":false,
"bdRestricted":true,
"profilePermission":"PUBLIC",
"uri":"https://social.yahooapis.com/v1/user/CGGT5LNT7NXGFK64QW7FQN5UQM/profile",
"cache":true
}
}
I Found Solution!
You need to change your application's permission in the yahoo.
Url, which provide user info: https://social.yahooapis.com/v1/user/me/profile
And don't forget to add header Authorization: Bearer [your_access_token]