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)
Related
I am trying to consume a RESTFUL web service using Java(HttpURLConnection and InputStream).I am able to print the response using BufferedReader, but it returns a response header as well and the format is causing issues to convert it to a Java POJO.
I tried using a URLConnection and then retrieving the input stream and passing it to the ObjectMapping(provided by Jackson)
final URL url = new URL("url");
final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.setRequestMethod("GET");
final ObjectMapper objectMapper = new ObjectMapper();
MyData myData = objectMapper.readValue(uc.getInputStream(), MyData.class);
Error Message : "No content to map due to end-of-input\n"
In your code you don't show where you actually read the data and where you declared and filled your output variable. As code is now it seems to be the incorrect reading from your rest service. But instead of writing your own code to read fro rest url I would suggest to use the 3d party library that does it for you. Here is few suggestions: Apache Http Client, OK Http client and finally my favorite - MgntUtils Http Client (library written and maintained by me) Here is the HttpClient javadoc, Here is the link to The latest Maven artifacts for MgntUtils library and here MgntUtils Github link that contains library itself with sources and javadoc. Choose some Http Client and read the content using that client and then you can use the content.
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/
I'm trying to retrieve a resource from web service, but get this warning:
WARNING: Unable to find a converter for this representation : [application/repo.foo+xml]
And my code returns null entity. Here is code
Engine.getInstance().getRegisteredClients().clear();
Engine.getInstance().getRegisteredClients().add(new HttpClientHelper(null));
Engine.getInstance().getRegisteredConverters().add(new JacksonConverter());
ClientResource resource = new ClientResource(path);
ChallengeScheme scheme = ChallengeScheme.HTTP_BASIC;
ChallengeResponse auth = new ChallengeResponse(scheme, "user", "password");
resource.setChallengeResponse(auth);
Repo entity = resource.get(Repo.class);
System.out.println(entity);
UPDATE
My attempts which unfortunately don't work:
resource.getRequestAttributes().put("org.restlet.http.headers", new MediaType("application", "application/repo.foo+xml"));
resource.setAttribute("Content-Type", "application/repo.foo+xml");
There is some confusion in your question.
You are writing a client. You can tell the client to set an accept header. Put simply, this is a hint to the server about what content type you'd like the response to be in. JSON, HTML, XML, whatever. The server can either honour this, send you it's best guess or ignore it completely.
You can try setting the accept header to "application/javascript" and see how it responds. If it continues to send "application/repo.foo+xml" then you will probably be able to parse it with the jackson xml databind package. You may have to register the media type and converter with the client so it knows which converter to use to serialise the object.
I recently moved over to Java and am attempting to write some REST tests against the netflix REST service.
I'm having an issue in that my response using rest assured either wants to send a gzip encoded response or "InputStream", neither of which provide the actual XML text in the content of the response. I discovered the "Accept-Encoding" header yet making that blank doesn't seem to be the solution. With .Net I never had to mess with this and I can't seem to find the proper means of returning a human readable response.
My code:
RestAssured.baseURI = "http://api-public.netflix.com";
RestAssured.port = 80;
Response myResponse = given().header("Accept-Encoding", "").given().auth().oauth(consumerKey, consumerSecret, accessToken, secretToken).param("term", "star wars").get("/catalog/titles/autocomplete");
My response object has a "content" value with nothing but references to buffers, wrapped streams etc. Trying to get a ToString() of the response doesn't work. None of the examples I've seen seem to work in my case.
Any suggestions on what I'm doing wrong here?
This has worked for me:
given().config(RestAssured.config().decoderConfig(DecoderConfig.decoderConfig().noContentDecoders())).get(url)
I guess in Java land everything is returned as an input stream. Using a stream reader grabbed me the data I needed.
Until its version 1.9.0, Rest-assured has been providing by default in the requests the header "Accept-Encoding:gzip,deflate" with no way of changing it.
See
https://code.google.com/p/rest-assured/issues/detail?id=154
It works for me:
String responseJson = get("/languages/").asString();
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