GWT RequestBuilder POST JSON application/json - json

I'm trying to send JSON data to a server.
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
builder.setHeader("Content-Type", "application/json");
builder.setRequestData(getJSONString());
builder.setCallback(myCallbackObject);
builder.send();
I do this in eclipse and I saw in the TCP/IP Monitor that my JSON Data is not transmitted as post in the request. If I ask for
builder.getRequestData();
I can see the JSON data is right there.
What do I need for the data to get on the server?

You might be running into the browser's same-origin policy if the url that you are attempting to connect to is not from the same origin as your GWT nocache.js file. Is your callback's onFailure() being called? Also, see if Request.getSatusCode() returns 0, which is indicative of SOP problems.

To simply post JSON data with HTTP post, you can use GWT Overlay Types to define a post method using JQuery. A possible snapshot:
public static native void post(String json) /*-{
var data = JSON.parse(json);
$wnd.$.post(url, data);
}-*/;
I don't know if it is necessary to add JQuery to your HTML. I did, and worked. You can do this by adding the following line to your .html file:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Then, you can simply call that method in your java code:
post(json);
(:

Related

Yii2 HttpClient: Access Request instance from Response instance

Using yii2-httpclient, what is the correct way to access the corresponding yii\httpclient\Request instance from the resulting yii\httpclient\Response object?
I am trying to write a custom XML parser which needs to know what URL it is parsing. It does not seem to be possible to access the original Request (through which I could get the URL) from a parser instance (only the Response).
I have considered utilizing yii\httpclient\Client::EVENT_AFTER_SEND to copy the request into a variable, but that would not be thread-safe, so I need a better solution.
If your parser needs to know URL of request to parse response, it is probably not a parser and you're overusing parser API and ParserInterface. I suggest to create some component which will wrap and hide all request-response-parser logic. Then you will be able to implement custom parser and call it manually:
public function get($url) {
$client = new Client();
$response = $client->createRequest()
->setUrl($url)
->send();
return (new MyParser($url, $response))->getContent();
}

Twitter OAUTH Acces Token Response in JSON

I'm using Twitter's REST API to authorize an app. I just authorized the app with
https://api.twitter.com/oauth/authorize
and got an oauth_verifier from the redirect uri.
Then I just used
https://api.twitter.com/oauth/access_token
to get an access_token.
The problem is that the format of response I got from this method is text/plain. It's just like
oauth_token=783897656863051776-5hQfcJTv4FzFpPcyVRbnjPUbJXR29&oauth_token_secret=MViTPOOCaHNZrW6HTIFZ340bq1rutJKL8oqkBxRp2aiW&user_id=783897656863051776&screen_name=sWest&x_auth_expires=0
My query is that how to get the response in application/json format.
Any help will be appreciated !!!
You will need to parse it like application/x-www-form-urlencoded content, any language with HTTP Client libraries should provide this functionality. But it isn't clear what language and libraries you are using.
This example uses joauth library to parse
protected static Map<String, String> parseTokenMap(String tokenDetails) {
KeyValueHandler.SingleKeyValueHandler handler =
new KeyValueHandler.SingleKeyValueHandler();
KeyValueParser.StandardKeyValueParser bodyParser =
new KeyValueParser.StandardKeyValueParser("&", "=");
bodyParser.parse(tokenDetails, Collections.singletonList(handler));
return handler.toMap();
}

get json data from a https webpage

I like to get json data from a external webpage and use this data in my Xpages.
the external website have the protocol https.
so I can't use
var http_request = new XMLHttpRequest();
http_request.open("GET","XX");
has anybody a hint for me?
Alternatively you could use JSONP for your GET request:
http://dojotoolkit.org/reference-guide/1.8/dojo/io/script.html
Get it in backend with f.e. an XPage and HttpURLConnection class. This XPage can serve the JSON data to the client so you can use XMLHttpRequest.
you can use XMLHttpRequest object for Https protocol.
see https://stackoverflow.com/a/6301294/1029621

Play Framework Cross Domain Web Service

I've been trying to create a Web Service with play framework. I've searched some tutorial and resource about this and end up using the renderJSON() method to provide JSON RESTful web service.
But, there seems to be a problem with that when I try to consume the web service with JQuery. If I use JSON, it fails with this error Origin http://localhost is not allowed by Access-Control-Allow-Origin. Which seems to be a cross-domain problem. Then I try to use JSONP as the datatype when JQuery trying to consume the web service, again there's an parseError problem.
After some research, I found that to provide a web service to the JSONP request. We need to provide something like a callback function. So it's not enough to return only the JSON object to the client. If I'm not mistaken, The format should look something like {#callback-function}{#JSON-data}
How to make a Cross-Domain web service in Play Framework? Is there any workaround for this?
Is there anyway to keep the JSON format of a/a list of object to a string instead of render the object as JSON directly as done by calling renderJSON()?
Here is what I did. In my routes I set the format of the response to javascript with:
GET /api/projects.json Api.projects(format:'json')
Then for the controller in Api I used flexjson and did this:
public static void projects(String p) {
JSONSerializer json = new JSONSerializer();
List<Project> projects = Project.all().fetch(3);
renderJSON(p + '(' + json.serialize(projects) + ')');
}
So now jsonp calls can be made by hitting /api/projects.json?p=whatever and the return will be:
whatever([{"your":"json"}])
You can also use flexjson to only serialize the parts of the object that you want to expose.
Testing it with jquery:
$.ajax({
url: "http://api/projects.json",
dataType: "jsonp",
jsonp : 'p',
crossDomain : true,
success: function(data){
console.log(data);
}
});
This is working great but you can use Gson object directly instead of the flexjson object.

How do I return raw html from a WCF WebAPI WebGet

I have a self-hosted WCF service running as a windows service using the WebAPI to handle the REST stuff and it works great.
I realise that I should really use IIS or similar to dish out actual web pages, but is there ANY way to get a service call to return "just" html?
Even if I specify "BodyStye Bare", I still get the XML wrapper around the actual HTML, ie
<?xml version="1.0" encoding="UTF-8"?>
<string> html page contents .... </string>
[WebGet(UriTemplate = "/start", BodyStyle = WebMessageBodyStyle.Bare)]
public string StartPage()
{
return System.IO.File.ReadAllText(#"c:\whatever\somefile.htm");
}
Is there any way to do this or should I give up?
The bodystyle attribute has no effect on WCF Web API. The example below will work. It's not necessarily the best way of doing it, but it should work assuming I didn't make any typos :-).
[WebGet(UriTemplate = "/start")]
public HttpResponseMessage StartPage() {
var response = new HttpResponseMessage();
response.Content = new StringContent(System.IO.File.ReadAllText(#"c:\whatever\somefile.htm"));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
It would probably make more sense to read the file as a stream and use StreamContent instead of StringContent. Or it is easy enough to make your own FileContent class that accepts the filename as a parameter.
And, the self-host option is just as viable way to return static HTML as using IIS. Under the covers they use the same HTTP.sys kernel mode driver to deliver the bits.
You'll have to use a formatter that accepts "text/html" as content type and request the content type "text/html" in your request header.
If you don't add a formatter that handles the text/html, Web API falls back to the XML-formatter as default.
In your case the formatter doesn't need to format anything but just return your return value as you're returning formatted html already.