Reputation: 2468
Working with an api that gives me an access token which works only with client ip, so I`m trying to make a request to that external site on client and return the JSON response to my server. The question is how to make the request and store JSON on client so I could send it to server then.
Thank you
Upvotes: 1
Views: 890
Reputation: 898
Take a look at Vaadin's
Integrating JavaScript Components and Extensions
here:
https://vaadin.com/docs/-/part/framework/gwt/gwt-javascript.html#gwt.javascript.rpc
You can create a JavaScript connector component that you can then use to make RPC's like so:
@JavaScript({"mycomponent-connector.js"})
public class MyComponent extends AbstractJavaScriptComponent {
public MyComponent(){
// when you create the component
// add a function that can be called from the JavaScript
addFunction("returnResponse", new JavaScriptFunction() {
@Override
public void call(JsonArray arguments) {
String response = arguments.getString(0));
// do whatever
}
});
}
// set up a way to make the request
public void makeRequest(String url) {
callFunction("makeRequest", url);
}
}
with the JavaScript file mycomponent-connector.js
(using XMLHttpRequest
example):
window.com_example_mypackage_MyComponent =
function() {
var connector = this;
// add a method to the connector
this.makeRequest = function(theUrl){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
connector.returnResponse(xmlHttp.responseText);
}
};
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
};
Calling the method MyComponent.makeRequest("myurl")
on the server side will fire the makeRequest
method on the client. When the response is returned we call connector.returnResponse(xmlHttp.responseText)
to send this back to the server and be handled by "returnResponse"
function added in the constructor of MyComponent
.
Upvotes: 3