I have a Play! application and from the JavaScript we now have run in to the Same Origin Policy Problem.
What I want is that JavaScript ajax calls go to our own server and that this server again route the json call to the external REST API.
My JavaScript use ajax to this url:
$.getJSON("http://mydomain.com/users", function(users) {
//callback
});
How can I easly make the server route to lets say:
public void getUsers(){
// result = call www.otherdomain.org/api/users.json What to do here?
renderJson(result);
}
and the return the response?
Or can it be done dynamically somewhere by directly rerouting?
here comes an example for doing async http calls (e.g. to facebook api)
WSRequest req = WS.url("https://graph.facebook.com/100001789213579");
Promise<HttpResponse> respAsync = req.getAsync();
HttpResponse resp = await(respAsync);
JsonElement jsonResp = resp.getJson();
JsonObject jsonObj = new JsonObject();
jsonObj.add("facebook-response", jsonResp);
renderJSON(jsonObj);
You can use the WS class to call another URL as a web service and retrieve the answer.
See an example here
Related
I'm new to the java rest CXF client. I will make various requests to a remote server, but first I need to create a Ticket Granting Ticket (TGT). I looked through various sources but I could not find a solution. The server requests that I will create a TGT are as follows:
Content-Type: text as parameter, application / x-www-form-urlencoded as value
username
password
I create TGT when I make this request with the example URL like below using Postman. (URL is example). But in the code below, I'm sending the request, but the response is null. Could you help me with the solution?
The example URL that I make a request with POST method using Postman: https://test.service.com/v1/tickets?format=text&username=user&password=pass
List<Object> providers = new ArrayList<Object>();
providers.add(new JacksonJsonProvider());
WebClient client = WebClient.create("https://test.service.com/v1/tickets?format=text&username=user&password=pass", providers);
Response response = client.getResponse();
You need to do a POST, yet you did not specify what your payload looks like?
Your RequestDTO and ResponseDTO have to have getters/setters.
An example of using JAX-RS 2.0 Client.
Client client = ClientBuilder.newBuilder().register(new JacksonJsonProvider()).build();
WebTarget target = client.target("https://test.service.com/v1/tickets");
target.queryParam("format", "text");
target.queryParam("username", "username");
target.queryParam("password", "password");
Response response = target.request().accept(MediaType.APPLICATION_FORM_URLENCODED).post(Entity.entity(yourPostDTO,
MediaType.APPLICATION_JSON));
YourResponseDTO responseDTO = response.readEntity(YourResponseDTO.class);
int status = response.getStatus();
Also something else that can help is if you copy the POST request from POSTMAN as cURL request. It might help to see the differences between your request and POSTMAN. Perhaps extra/different headers are added by postman?
Documentation: https://cxf.apache.org/docs/jax-rs-client-api.html#JAX-RSClientAPI-JAX-RS2.0andCXFspecificAPI
Similar Stackoverflow: Is there a way to configure the ClientBuilder POST request that would enable it to receive both a return code AND a JSON object?
I'm trying to write a simple server with SparkJava but I am having considerable difficulty serialize a long using Gson and transmitting the JSON to an OkHttp client program inside a GET handler. The server returns NULL, more specifically response.body.string() is
<html><body><h2>404 Not found</h2></body></html>
Any ideas on what the issue could be? thanks.
Here is the GET handler:
get("routingEngine/getDefaultRoute/distance", (request,response) ->{
response.type("application/json");
long distance = 100;
return gson.toJson(distance);
});
Here is the client code making the simple request (please disregard the parameters (requestParameters) being passed in along with the request, they just provide information to an irrelevant before filter):
// build url
HttpUrl url = new HttpUrl.Builder()
.scheme("http")
.host("127.0.0.1")
.port(4567)
.addPathSegment("routingEngine")
.addPathSegment("getDefaultRoute")
.addPathSegment("distance")
.build();
// build request
Request getDefaultRouteDistanceRequest = new Request.Builder()
.url(url)
.post(RequestBody.create(JSON,gson.toJson(requestParameters)))
.build();
// send request
Call getDefaultRouteDistanceCall = httpClient.newCall(getDefaultRouteDistanceRequest);
Response getDefaultRouteDistanceResponse = getDefaultRouteDistanceCall.execute();
// parse response
// testing
System.out.println(getDefaultRouteDistanceResponse.body().string());
The last line leads to the following output
<html><body><h2>404 Not found</h2></body></html>
The endpoint you created was a GET endpoint and the call being made is for POST.
In Latest Play JAVA (v 2.6) I am trying to fetch 3rd party restful api and process the response for further calculation in the controller. As the response type is a CompletionStage I am unable to convert it to usable JSON string from the response.
What I have tried,
final WSResponse r = (WSResponse) ws.url(domainUrl).setRequestTimeout(5000).get();
final JsonNode result = r.asJson();
But no help.
I also tried to fetch using java HttpURLConnection but there is no help either as the request is stopping for ssl skipping error, which only can be solved from play configuration.
Advance thanks!
Use plain Jackson to parse the body String:
final WSResponse r = ...;
Json.mapper().readValue(r, Type.class)
I am interested in writing a Java application that can access my OneNote notebooks via the OneNote API. I am not sure how to gain access to that API from within Java. Can anybody point me to an example of how to get started here? I use Eclipse as my development environment.
This as straightforward process.
The 3 steps would be:
1) create a OneNote application on the OneNote developper's page. More info here https://dev.onedrive.com/app-registration.htm. This is a one time action.
2) your java application should then provide an authentification mechanism and a tolken-refresh mechanism.
See this post for more info on the authentification mechanism part : Getting a OneNote token with Java. This post is about the OAuth 2.0 flow 'Authorization code grant flow'. More info here https://msdn.microsoft.com/en-us/library/hh243647.aspx#flows
3) your java application calls adhoc API Rest methods to retreive the needed informations.
Example to retrieve all your notebooks (using OkHttp for Http requests):
private final static String NOTEBOOKS_ENDPOINT = "https://www.onenote.com/api/v1.0/me/notes/notebooks";
public Notebooks readAllNoteBooks() {
try {
if (client == null)
client = new OkHttpClient();
Request request = createOneNoteRequest(a_valid_tolken, NOTEBOOKS_ENDPOINT);
Response response = client.newCall(request).execute();
JsonObject content = UrlHelper.parseResponse(response);
System.out.println(content);
return Notebooks.build(content.get("value"));
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Request createOneNoteRequest(String mAccessToken, String url) {
Request.Builder reqBuilder = new Request.Builder();
reqBuilder.url(url);
reqBuilder.header("Authorization", "Bearer " + mAccessToken);
return reqBuilder.build();
}
NoteBooks and NoteBook are 2 tiny classes matching the key attributes from the OneNote objects.
Microsoft has provided REST apis for accessing One note functionalities like creating and accessing notes. See OneNote Rest API reference.
singrass,
In addition to the above replies, the Android OneNote API sample may also help you. There is no OneNote application class that you can create (unless you want to create your own). You simply call the API through the HttpClient. If you are unfamiliar on how to call REST APIs in Java in general, this thread may help you.
-- James
I'm working on an ESB project and I need to call a REST service using a POST request. HttpRouter seems to be the right way to do it since it supports both GET and POST methods but I can't find a way to inject parameters inside my call.
How can I do that ?
You can try Apache HTTP library. It's very easy to use and have comprehensive set of class needed to manipulate HTTP request.
Found the answer... It was pretty dumb. All you need to do is to inject parameters inside the Message object and they will be in the body of the request. Here is a sample code created by JBoss and found from a unit test of HttpRouter :
final ConfigTree tree = new ConfigTree("WrappedMessage");
tree.setAttribute("endpointUrl", "http://127.0.0.1:8080/esb-echo");
tree.setAttribute("method", "post");
tree.setAttribute("unwrap", "false");
tree.setAttribute("MappedHeaderList", "SOAPAction, Content-Type, Accept, If-Modified-Since");
HttpRouter router = new HttpRouter(tree);
Message message = MessageFactory.getInstance().getMessage(type);
message.getBody().add("bar");
Message response = router.process(message);
String responseBody = (String)response.getBody().get();
String responseStr = null;
if (deserialize)
responseStr = Encoding.decodeToObject(responseBody).toString();
else
responseStr = responseBody;
return responseStr;