PlayFramework. JSONP view. How? - java

I need that controller return JSONP response.
Something like this:
jsonp123({"name" : "Remy", "id" : "10", "blog" : "http://site.com"});
I know, that PlayFramework can send response as html Template, JSON, XML... but how send JSONP response?
Thanks.

You can take a look at how it's done for JSON (renderJSON() throws a RenderJson object) and implement JSONP response in a similar way. The only difference is that you need to surround Gson output with a function call and that content type should be text/javascript.

You can set the header type to "text/javascript" and then call renderText. (The render methods only set the mime type if you don't.)

Related

What type of content/format is this (Response that i am getting from an API)?

What type of object/content is the following piece of response from an API
The Content-Type of the API response is coming as text/HTML
a:3:
{s:6:"status"
;i:1;
s:3:"msg"
;s:22:"Transaction is Pending"
;s:6:"result";
}
Ideally I am expecting a way to make this object into a JSON object or a way in which Java is able to handle such objects.

Jetty servlet: How can I forward GET request with parameters as POST request with JSON body?

My web clients send GET requests with URL query parameters. The receiving App can only accept POST requests with JSON body. I would like to embed a jetty servlet to the receiving App which converts GET requests to POST request, with url parameters being converted to json format body.
Input GET url for example: http://localhost:8081/?key_1=value_1&key_2=3value_2...&key_n=value_n
Expected POST json payload: {"key_1":"value_1", "key_2":"value_2", ..."key_n":"value_n"}
Could you please illustrate how to implement such functions?
I`ve worked with other programming languages, but am completely new to java. I really really appreciate your help.
Thanks and best regards,
Fischlein
You can read all the query string parameter and put it into HashMap. Then serialize this hashmap using jackson-json api or google gson api.
Jackson Reference Url :
http://wiki.fasterxml.com/JacksonHome
Read the parameters from the get request, create a json string and post it with a utility library like http://hc.apache.org/httpclient-3.x/

Parse variables from json url using jQuery

How I can parse parameters like "city" from json?
I have url like this: http://api.db-ip.com/addrinfo?addr=8.8.8.8&api_key=key, this return me this:
{
"address":"8.8.8.8",
"country":"US",
"stateprov":"California",
"city":"Mountain View"
}
I want to apply city (or country) variable to <input type>, to show visitors some info about location.
If you just want to load that JSON object and access the "city" field, use jQuery's getJSON method to get a native JS object in response.
$.getJSON( "http://api.db-ip.com/addrinfo?addr=8.8.8.8&api_key=key", function(data) {
// do something with data.city;
});
However, in your case, you're trying to make a cross-domain JSON request -- not allowed. Since db-ip.com doesn't allow it, you'll have to proxy the request using PHP.
Set up "dbip.php" on your server as a proxy (cf. http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html)
Then you just load JSON from dbip.php on your own server, which queries db-ip.com for you. The browser is happy because the AJAX request it makes doesn't cross domain names.
var response={
"address":"8.8.8.8",
"country":"US",
"stateprov":"California",
"city":"Mountain View"
};
$("#city").val(response.city);

Post JSON Data From Javascript To Java

I'm in need of some desperate help. I've been at this for 4 hours, and I'm getting pretty worn out. :/ Here's my situation:
I have a Javascript application that is making a POST request (using jQuery $.post) to an external site. On the external site I have Apache Camel running with Jetty to expose it to the web. The web services I wrote in Camel expect JSON data for all of the requests. For instance, one request needs an id, so I send it {"id": 10}.
Here's my issue: it doesn't work from Javascript. I have a few different tools that will send post requests for me (like the Poster extension for browsers). If I use Poster and set the body to {"id": 10}, it works just fine. I get that exact string in the service.
But, if I post from Javascript, I get something different. Posting the JSON object will give me the string "id=10" on my service side. (It's OK for this scenario, but I will need actual JSON objects eventually.) If I stringify the JSON object, I get the JSON string, only all of the characters are escaped. (Ex. "%7Bid%33...").
I swear I've tried every method possible for posting the data, but I either get the weird already parsed JSON, or the escaped string (or nothing at all). Is there some way I can have Javascript NOT parse the JSON object and just send it (like my posting tool does)? If not, is there a safe, efficient way to un-escape the JSON string that I get?
I really appreciate any help.
I feel like we need a little bit more information, but take a look at this javascript plugin. It may be your solution: https://github.com/flowersinthesand/jquery-stringifyJSON
Try using jQuery.ajax and setting processData to false (defaults to true):
$.ajax({
url: '/where/to/post',
type: 'POST',
data: {"id": 10},
processData: false
});
Usually, jQuery converts anything in data to query string format like id=10. The processData flag tells jQuery to interpret it literally as a json hashmap.
Posting the JSON object will give me the string "id=10" on my service side.
Javascript does not do your this conversion, so your server does it.
It is likely that your server reacts differently based on the content-type of your POST e.g. application/json vs text/plain or text/html, a common feature of REST based services.
The answers here gave me a few hints, but ultimately, it was a lot of tweaking before it would work correctly. I had to do 3 things:
Add processData: false.
Turn the JSON object into a JSON string. The request wouldn't fire if I left it as an object (even if I changed contentType to application/json).
Change the contentType to text/plain. This sent it as a raw string.
And that's what did the trick. I now get the JSON string I want on the server side.

Send error message as JSON object

I have two servlet: first servlet is similar to a client and creates an HttpURLConnection to call the second servlet.
I would like send a special error, formatted like a JSON object, so I call sendError method in this way:
response.sendError(code, "{json-object}")
But in the first servlet when I read error with getResponseMessage method I just get standard HTTP message and not my json object as a string.
How I can get my json string?
From the HttpServletResponse#sendError() javadoc:
The server defaults to creating the response to look like an HTML-formatted server error page containing the specified message, setting the content type to "text/html", leaving cookies and other headers unmodified. If an error-page declaration has been made for the web application corresponding to the status code passed in, it will be served back in preference to the suggested msg parameter.
So with this approach you have no other option than extracting the message from the HTML response yourself. JSoup may however be useful in this.
To achieve what you want, you need to set the error code and write the response yourself, e.g.
response.setStatus(code);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Instead of code you could by the way also use one of the HttpServletResponse.SC_XXX constants for this.

Categories