I'm consuming a REST api using the RestBuilder plugin. I get a response where the body is compressed:
Content-Encoding=[gzip]
Does groovy/Grails provide any easy access / native methods for decoding gzip compression? The only thing I found is the native Java zip api (ex. GZIPInputStream). Does someone have a better idea?
basically, you have 2 options here:
GZIPInputStream
configure GZIP-decompression in tomcat, see here
Spring and HttpComponents will handle the decoding automatically:
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().build());
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
ResponseEntity<String> response = restTemplate.exchange(
"some/url/", HttpMethod.GET, new HttpEntity<Object>(requestHeaders),
String.class);
Related
The vertx implementation of calling / invoking / consuming the REST APIs through requestAbs method
of io.vertx.core.http.HttpClient class from vertx-core-3.2.0.jar results in HTTP Error :: 302 and Response Data as HTML Erro Response .
Not sure how the requestAbs method behaves as there's no exception thrown and it does not write any logs as well.
Also source code attached for this method with vertx jars. Suspect, if the method implementation has a bug?
The same REST API calls are success with Browser / POSTMAN.
The traditional approach with Apache HTTPClient for REST Calls are success, then I doubt why not with vertx framework.
Any solution / modification in code snippet below is much appreciated.
Thanks
Code
Your code is a bit confusing (it looks like variables names are not always the same).
Anyway, you will manage to do what you want with that code:
final HttpClient httpClient = vertx.createHttpClient();
final String url = "http://services.groupkt.com/country/get/iso2code/IN";
httpClient.getAbs(url, response -> {
if (response.statusCode() != 200) {
System.err.println("fail");
} else {
response.bodyHandler(b -> System.out.println(b.toString()));
}
}).end();
Hope this will help.
I have a spring-mvc project as a frontend project. My datasources are accessed by a second javaee project. This backend grands access to all data my frontend requires, by providing REST services. The REST-Service provides objects, by returning XML. This XML will then get marshaled by my frontend.
So when my frontend project requires current data, I create an HttpUrlConnection, then I call the REST-Service of my backend.
E.g. I want to get a collection of all movie objects:
URL url = new URL(URLSAFE.REST_ALL_MOVIES);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/xml");
connection.getResponseCode();
InputStream is = connection.getInputStream();
Source sauce = new StreamSource(is);
JAXBContext jaxbContext = JAXBContext.newInstance(Movies.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
JAXBElement<Movies> e = unmarshaller.unmarshal(sauce, Movies.class);
Movies m = e.getValue();
this.MOVIELIST = m;
connection.disconnect();
After I added some remote ejb lookups for logging services, I came up with the idea to use rmi for passing objects. However I learned I cant cast the object to my frontend and that there is a big difference between a local object and a object you access by rmi.
But what would be a good attempt for passing objects between servers? I need to pass objects to the frontend because I got to use them with JSP.
I would suggest to take a look at this Spring.io guide. Usage of RestTemplate can remove a lot of boilerplate you have in example, and map REST resources onto POJOs. XML shouldn't be any barrier, because Spring should significantly help you abstract it.
I'm developping an Eclipse RCP Application that have to display in a Treeview the collections of a DataBase.
The collections of the DataBase are provided by a REST API.
So, what i have to do is to call the REST API by given the URL and the KEY and display result (The collections) in the Treeview.
What i know about REST API is that it's used (most of the time) in web applications, but it's not the case for me.
Does anybody know how to call a REST API from an Eclipse RCP Application ?
Does someone have an experience with RCP and REST API ?
Thanks in advance.
Ismail
You should be able to use whatever java rest client you want. I personnaly preferred using jersey because sometimes using Spring Framework inside Eclipse can be painful.
It worked for me adding all these librairies :
lib/jsr311-api-1.1.1.jar,
lib/jersey-client-1.19.jar,
lib/jersey-core-1.19.jar,
lib/jersey-json-1.19.jar,
lib/jackson-core-asl-1.9.2.jar,
lib/jackson-jaxrs-1.9.2.jar,
lib/jackson-mapper-asl-1.9.2.jar,
lib/jaxb-api-2.2.2.jar,
lib/jaxb-impl-2.2.3-1.jar,
lib/jackson-xc-1.9.2.jar
And a simple call is as follow :
try {
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
WebResource webResource = client.resource("http://localhost:8080/getMyObject");
ClientResponse response = webResource.get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
MyObject output = response.getEntity(MyObject.class);
} catch (Exception e) {
//Handling errors
}
JSONConfiguration.FEATURE_POJO_MAPPING is for the auto mapping to json using jersey-json and jackson-*.jar
To call the RestAPi, i've used the SpringFramework using this :
org.springframework.web.client.RestTemplate and its methods.
Recently I was using RestSharp to consume my Restful Resouce. and expected exchanging data with JSon between server and client. Below is my C# code.
var client = new RestSharp.RestClient();
var request = new RestRequest(sUrl,Method.POST);
request.RequestFormat = DataFormat.Json;
request.Timeout = TIME_OUT_MILLISECONTS ;
request.AddHeader("Content-Type", "application/json");
request.AddBody(new { appID = sAppId, loginName = sUserName, password=sPassword });
var response = client.Execute(request);
string s=response.Content;//It is always XML format.
The result is not what I expected for(Json data format), although I had set the RequestFormat Json and add Http header Content-Type. So I decided to use the .Net Reflector to found out What happened in the RestClient.Execute method. Here is the code of the method.
public RestClient()
{
...
this.AddHandler("application/json", new JsonDeserializer());
this.AddHandler("application/xml", new XmlDeserializer());
this.AddHandler("text/json", new JsonDeserializer());
this.AddHandler("text/x-json", new JsonDeserializer());
this.AddHandler("text/javascript", new JsonDeserializer());
this.AddHandler("text/xml", new XmlDeserializer());
this.AddHandler("*", new XmlDeserializer());
...
}
I have some questions about it:
As the RestClient adds many kinds of Content-Type into the HttpWebRequest. Is it right way to build a Request? And I think Maybe that is the reason why Response.Content always XML.
I don't know why the RestClient needs to build a HttpWebRequest like that. Any meaning to do that?
If we specified both JSon and XMl message format in a Http Request, which one works finally? Is it allowed?
Thanks. Have a good day.
RestSharp will use the correct handler based on the content type of the response. That's what those AddHandlers are doing; its configuring the RestClient to accept certain content types in the response and mapping those types to deserializers. Normally you would want to set an accept header for the json content type which notifies the server to send json in the response.
request.AddHeader("Accept", "application/json")
Of course, this assumes that the server you are hitting is configured to respond with json.
Hi Can anyone let me know where I can find sample RESTFul APIs so that I can have hands on experience working on them using GET/POST/DELETE methods.
Thanks.
If you have an idea about Java, Servlet, Wildfly / Tomcat server, Mysql then you can create a basic program for Get / Post Method and deploy on the local server.
You will learn to create basic API also. The best way you install eclipse and integrate server. With Eclipse, you can easily create Servlet as it provides template and web.xml generate automatically.
Create a basic object Class. Call it in servelet fill some data.
Convert it to JSON by using GSON
#WebServlet(asyncSupported = true, urlPatterns = { "/School_getEmployee" })
public class School_Employee_servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Gson gson = new GsonBuilder().serializeNulls().create();
String json = gson.toJson(Object);
PrintWriter out = response.getWriter();
out.println(json);
}
Now you can use this servlet as API for testing.
You can use JSON-SERVER, I'm using these to make GET/PUT/POST/DELETE