Prevent encoding in #FormUrlEncoded retrofit - spring

I need to make a post request such that the json data passed, has key pair value,where the key is data.
For example, if i use jquery as below, data is the key.
$.ajax({
url: “/hello",
data:{ data: JSON.stringify(dataObject) },
type:"POST",
dataType:"json"
});
which is equivalent to
data:{ data: {“firstName”:”john”,"lastName”:”doe”}}.
I am using java spring retrofit, to accomplish the similar. In order to pass the key, i am using #FormUrlEncoded and #Field("data") TypedString userInfo
My retrofit interface is as below
public interface userInfoService {
#FormUrlEncoded
#POST(“/hello")
public Response userInfo(#Field("data") TypedString userInfo);
where TypedString is {"firstName":"john","lastName":"doe"}
However, the request looks something like this
data=%7B%22firstName%22%3A%22john%22%2C%22lastName%22%3A%22doe%22%7D, since it form url encoded.The 3 party api can see the data key, but since it has "=" instea of ":", it cant be parsed
How, do i get the request to avoid = and actually send a decoded request.
I have also tried to use #Body instead of #FormUrlEncoded and #Field. Where #Body has TypedString as {data: {“firstName”:”john”,"lastName”:”doe”}}, but for some reason the 3 party api is not able parse the data key.

Related

Axios AJAX call nulls parameter

I use Vuejs to create my frontend for my project.
At the creation of one component ('TimeCapsy.vue'), I make an AJAX call to my backend like this:
created: function () {
if (verify.verify_login()) {
let token = this.$cookies.get('jwt_us_cas');
let params = {'jwt': token};
console.log(params);
axios({
method: 'post',
url: dev.HOST+'getuserinfoobject',
params: queryString.stringify(params)
})
.then(response => {
console.log(response.data)
})
}
}
As you can see I use the
this.$cookies.get('jwt_us_cas');
to get the a json web token, that I set on the client at the login.
I use the queryString Library to stringify my parameters for my request.
I also tried it without the queryString.stringify(params) call, but I get the same error, e.g. the parameter still turns into null.
When I look at the console log, where I check the params variable, I get this output:
{jwt: "my token comes here"}
So I can see, that it gets the correct value from the cookie.
But when I check the answer from my backend (PHP), I get this error:
Undefined index: jwt in <b>D:\casb\public\index.php</b> on line <b>52</b>
Of course I know that it means, that jwt is null, but I can't understand why.
As I said, right before I make the call I check the params and it shows the token.
I checked the endpoint with Postman and the token as the jwt parameter and it returned a successfull call with the correct answer.
A correct answer is basically just a nested object with some information in it.
My PHP endpoint is pretty basic too:
Router::add('/getuserinfoobject', function () {
$response['response'] = User::getUserInfoObject($_POST['jwt']);
echo json_encode($response);
}, 'post');
So I guess that right before or in my call it nulls my parameter. But I can't understand how, since I make a lot of requests and never had this problem.
From axios docs
params are the URL parameters to be sent with the request
Which means, you should get the value with PHP $_GET.
Or $_REQUEST (which stores both $_GET, $_POST. Also $_COOKIE).
The other hand, you can use data key as docs says
data is the data to be sent as the request body
Only applicable for request methods PUT, POST, and PATCH
So the value would be available in $_POST
axios({
method: 'post',
url: dev.HOST+'getuserinfoobject',
data: {
jwt: token
}
})

Using the Rally API to change the rank of an item

I am trying to use the Rally web service API to reorder 2 items.
From looking at the documentation i should be able to do:
$.ajax({
url: https://rally1.rallydev.com/slm/webservice/v2.0/task/12345?rankAbove=/slm/webservice/v2.0/task/56789,
type: 'PUT',
headers: { Authorization: Basic mytoken },
success: function(data) {
//do something
}
});
but i'm getting an error:
Cannot parse input stream due to I/O error as JSON document: Parse error: expected '{' but saw '￿' [ chars read = \u003E\u003E\u003E￿\u003C\u003C\u003C ]"
The documentation doesn't seem to reveal what I could be doing wrong.
Cheers for your help
You won't be able to use basic auth to do this because there is an additional CSRF token you need to pass. I think you can make it work with an api key though:
headers: { zsessionid: myToken }
You didn't have any issues with reading data because the CSRF protection only kicks in when attempting to modify data.
For what it's worth, the App SDK generally handles most of this complexity for you. It looks like you're using jquery in your app here instead, which is why you need to do this low level stuff...

sendAJAX data parameter in CasperJs

again, I got another problem with casperjs, now with sendAJAX function.
It says that sendAJAX has 5 parameters which are these followings :
url: The url to request.
method: The HTTP method (default: GET).
data: Request parameters (default: null).
async: Flag for an asynchroneous request? (default: false)
settings: Other settings when perform the AJAX request (default:
null)
So, it says the data method is object so, it should be filled with :
var data = new Object();
data.amount= 15;
and also with this one,
var data = {amount:15};
but there were no successful value send to my web service (always send 0 as value, but ajax request successful, even returning the json data) which has an url like this
"http://localhost:9000/TempCountryAmountREST/setCountryAmount"
It will be succeed if I direct bind my data variable to my url like this :
"http://localhost:9000/TempCountryAmountREST/setCountryAmount?amount="+amount
[UPDATE]
The TempCountryAmountREST is my controller name and setCountryAmount is my function inside my controller.
[UPDATE]
I forgot to include my usage of sendAJAX(), here is the code that I use :
return JSON.parse(__utils__.sendAJAX(wsurl, "POST" , data, false, { contentType: "application/json" }));
So how does I fill the data in the sendAJAX parameter?
Thanks in advance...
Sorry, I've found what the answer is.
I make some mistakes in contentType which I was set with contentType: "application/json" instead of contentType: "application/x-www-form-urlencoded" }
If we are looking about how ajax send the content from method send(), they were use x-www-form-urlencoded. See this for more detail
When we see through casperjs clientutils.js script, we should found how sendAJAX work.
On the `this.sendAJAX = function sendAJAX(url, method, data, async, settings) {
}
there are url construction logic which transformed our Object (if so) to x-www-form-urlencoded form. So that we need to set our contentType as application/x-www-form-urlencoded
Very well, thanks for your attention...

Sending JSON List Of Object to Spring MVC controller

I have an issue with sending a List Of Objects to Spring MVC controller .
The list of object is like this
[{"alias":"1",
"rue":"Rue de la Senette",
"codePostal":"78955",
"ville":"Carrières-sous-Poissy",
"rueComplement":""}]
And I send the above data with the following AJAX code:
$.ajax({
type : 'POST',
dataType : 'json',
contentType :'application/json',
url : $("#clientForm-add").attr('action'),
data : JSON.stringify(adresses.toArray()),
});
When I use this form of ajax, it worked for me and the format sended is as follow:
Request Payload :
[{"alias":"1",
"rue":"Rue de la Senette",
"codePostal":"78955",
"ville":"Carrières-sous-Poissy",
"rueComplement":""}]
Yes, even the above one is worked, when i send it like as follow:
$.ajax({
type : 'POST',
dataType : 'json',
contentType :'application/json',
url : $("#clientForm-add").attr('action'),
data : {adresseList : JSON.stringify(adresses.toArray())},
});
It doesn;t work for me. The sending data is look like
listAdresse=%5B%7B%22alias%22%3A%221%22%2C%22rue%22%3A%22Rue+de+la+Senette%22%2C%22codePostal%22%3A%2278955%22%2C%22ville%22%3A%22Carri%C3%A8res-sous-Poissy%22%2C%22rueComplement%22%3A%22%22%7D%5D
Response Headersview source
And, It gave an error: 400 bad request
Here, my controller
#RequestMapping(value = "creerlivraison/ajouterclientBD",method=RequestMethod.POST)
public String ajouterClientBD(#RequestBody Adresse[] listAdresse, Principal principal) {
for (Adresse adresse : listAdresse) {
System.out.println(adresse);
}
return "ok";
}
I want to know that "What is the difference between the two ajax request?", why the request payload is formatted when I wrap the data inside the braquets {} and specify listAddress.
Here is screen capture:
http://api.jquery.com/jquery.ajax/
data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
In this instance,
JSON.stringify(adresses.toArray()) is string, just keep the JSON format.
{adresseList : JSON.stringify(adresses.toArray())} is an object, so it is converted to a query string.

Making jQuery $.ajax call to Twitter API 1.1 search

Here is a very simple example of a call to Twitter's search API to get all tweets from a tag known to have tweets, #fml.
I believe I am correctly using the application-only authentication as explained here: https://dev.twitter.com/docs/auth/application-only-auth (see Step 3 for example of a call)
I am being asked for a solution that does not involve any server-side code so I am including the bearer code in the javascript, which isn't good to begin with, but....
I would expect this code to work. Instead it produces the error '400 (Bad Request)'. Any ideas?
$.ajax({
url: "https://api.twitter.com/1.1/search/tweets.json",
dataType: "jsonp",
data: "q=%23fml",
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Bearer XXmyBearerCodeXX");
},
success: function(json){ alert(json); }
});
EDIT 1 - Validated Twitter call
Using hurl.eu I was able to get a successful response from the API with the above query and Authorization header, so I assume this means my Twitter call is correct, just not set up correctly within jQuery.ajax(), but I just don't see what is missing.
You cannot set request headers using AJAX calls with dataType JSONP.
See this question: Set Headers with jQuery.ajax and JSONP?
The best solution is to use a server-side proxy to do the search for you. I know you are looking for a client only solution, but with this restriction, and with no way around CORS, this is how it seems to be done today for the Twitter API.
Edit It may be possible using a proxy like Yahoo's YQL if you don't have access to one.
on your severside create a jsp or servlet and from the client side make a JSON call to the .jsp/servlet and that will return back the json object to the javascript. In serverside use the twitter4j api.
sample code:
`
$.getJSON(http://localhost:8080/test.jsp?callback=?",
{
jspqueryStr : queryStr,
jspgeocodeStr : geocodeStr,
lat:latStr,
lan:lngStr,
radius:radiusStr,
}, displayResult);
//This function returns the data as json object from server.
function displayResult(data) {}
In the jsp the code is like below
<%
String jspqueryStr = request.getParameter("jspqueryStr");
String jspgeocodeStr = request.getParameter("jspgeocodeStr");
String diseasename = request.getParameter("jspqueryStr");
String lat = request.getParameter("lat");
String lan = request.getParameter("lan");
String radius = request.getParameter("radius");
Gson gson = new Gson();
String json = gson.toJson(tweetList);
json = request.getParameter("callback") + "(" + json + ");";
out.println(json);
public List<Status> searchstream(){
//here all the twitter4j api code to get the data
retrun tweetList;
}
%>
`

Resources