I have a rest service, not restfull.
The module is stateless and just expose some rest endopoints: receives a request, transform it, invokes external endopints, and then compose a Json response.
The thing is that the response is quite verbose, and some of the fields are quite big.
I've been asked to provide a filtering at request level, so that the response contains only the requested data.
Just to provide an example: my exposed method is a POST, and accept an image encoded BASE64, and the response too, can contain an image, and many other fields:
request: { image="<here a long BASE64 encoded request>"}
response: {result="success",
message="it was a success",
responseImage="<another base64 encoded image>",
longArray1=[
{first="...", second="...", third="..."},
{first="...", second="...", third="..."},
....many!
],
longArray2=[
{first2="...", second2="...", third2="..."},
{first2="...", second2="...", third2="..."},
....many!
]
}
What I want is avoid to reinvent the wheel. Is there a known pattern to make a query (adding something in the queryString, or in the Json request, and how) so that the consumer can choose in advance what fields to receive in response, and save bandwidth in the response?
The idea to have a Filter class is a good one. Your Filter class should provide fields which mirror the response object and use defaults for fields which are not provided. E.g. if a user of your api does not pass any json serialized filter object in their request, they should still receive data with the default filters. Extending your example, the request would look like
request: {
image="<here a long BASE64 encoded request>",
requestFilters:{
responseImage="<another base64 encoded image>",
longArray1={ firstFilter:"PASSED_ONLY",
secondFilter:"FAILED_ONLY",
....many!
},
longArray2={ // using defaults for firstFilter and secondFilter
thirdFilter="PASSED",
fourthFilter="FAILED",
....many!
}
......
}
}
Hope that helps.
Related
I want to hit a URL which contains data, i want to retreive this data using spring boot and convert it to AVRO format. data needs to be picked up in JSON format
data and url in one sentence raises alarm. Unless you have a particular need (usually legacy reasons) to use URL to send data, use requestbody for sending the data.
Remember, many browsers will have URL character limit even though http protocol doesn't talk about any
If you are adamant about sending Jsondata using url, either look into base64encode it and send and then base64decode it on serverside.
Or do URL encoding and Decoding . Because there is a highchance that the data might not be URL-safe
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 am getting different type of JSON response out of HTTP request API. There are might be couple of JSON format option coming back from API. For example it might be valid response with expected data but in some cases it might be internal server error detailed message.
At the moment I am using Gson to convert incoming string into the object, but since sometimes it comes as different format Gson not able to convert it as different template class is provided.
NOTE:
Error does not mean an exception. For example JSON body contain just information that authentication is failed for example, but call was made successfully and JSON body is VALID. HTTP is actually always successful and will be 200. Problem is that sometimes authentication might fail and it will return different JSON.
String response = restTemplate.getForObject(request, String.class);
ObjectResponse objResponse = gson.fromJson(response, ObjectResponse.class);
Could you please suggest better way of doing it so that I can handle different types of responses? Or maybe you know completely different way of doing it.
Thanks!
If you can't predict the structure of the response, map it to a tree of simple Java maps, arrays, and strings. The Jackson library supports this with 'readTree' methods. Once you look at the tree and decide what it is, you can then ask the library to map a tree to an object of a class.
One option is to make a class representing the JSON data, and deserialize into that. This way, if the data does not match that structure, you will get an exception.
When you try and create your object and it fails, catch the exception and try and decode it as an error - you can then deal with that case as you wish (and the potential case where it is neither the object you expect or a valid error).
Check HTTP Response Codes. If you receive a status code that isn't OK(200) then you shouldn't try to parse for a successful response. For instance you may check the code and handle response like this (the object types are not actual Java types, but are given to provide an example):
MyHttpResponse response = MyHttpHelper.execute(...);
int status = response.getMyStatusCode();
String responseData = response.getStringBody();
switch(status) {
case 200: {
//request is successful, parse valid data
break;
}
default: {
//request is not valid, parse error data
break;
}
}
I have some forms and databases that will fill up some POJO's with data. Using Json (gson) I"m going to upload the data to my web server. The server will send back a responses that will eventually be placed back in objects.
My question is, should I encode/decode my objects to json and then pass strings back and forth to my WebApi class? Or should I pass my WebApi class my object and have it pass back an appropriate response object (based on the method I call.)?
So at when I call my Api that has all the http conection stuff in it, it would look something like this.
myWebApi postSomeData( jsonData ); //
Should jsonData be a pojo that will be encoded into json string inside myWebApi or should I encode it into json and pass in a string.
Or in otherwords
String postSomeData( String jsonData){
web code here..
}
or
ResponsePojo postSomeData( PostData myData){
...
myMapper.MapFrom(myData); //converts pojo to json
...
webcode
}
At some point there will be images included in the data needed to be uploaded.
I would recommend using json for data transfer, it will make your services technology independent.
You can use flexjon to serialize java objects in a pretty direct way on the server side.
For images you will need to do post http POST anyway, this should be done separately from data submit since an error in a image upload should not result in data loss. Typically you'll associate the id of your data object in the uploaded image (or reversly), so you need to insert your object to db and wait for the response to insert the dependency id to your image.
Best Regards,
Zied Hamdi
http://1vu.fr
I'm in need of some desperate help. I've been at this for 4 hours, and I'm getting pretty worn out. :/ Here's my situation:
I have a Javascript application that is making a POST request (using jQuery $.post) to an external site. On the external site I have Apache Camel running with Jetty to expose it to the web. The web services I wrote in Camel expect JSON data for all of the requests. For instance, one request needs an id, so I send it {"id": 10}.
Here's my issue: it doesn't work from Javascript. I have a few different tools that will send post requests for me (like the Poster extension for browsers). If I use Poster and set the body to {"id": 10}, it works just fine. I get that exact string in the service.
But, if I post from Javascript, I get something different. Posting the JSON object will give me the string "id=10" on my service side. (It's OK for this scenario, but I will need actual JSON objects eventually.) If I stringify the JSON object, I get the JSON string, only all of the characters are escaped. (Ex. "%7Bid%33...").
I swear I've tried every method possible for posting the data, but I either get the weird already parsed JSON, or the escaped string (or nothing at all). Is there some way I can have Javascript NOT parse the JSON object and just send it (like my posting tool does)? If not, is there a safe, efficient way to un-escape the JSON string that I get?
I really appreciate any help.
I feel like we need a little bit more information, but take a look at this javascript plugin. It may be your solution: https://github.com/flowersinthesand/jquery-stringifyJSON
Try using jQuery.ajax and setting processData to false (defaults to true):
$.ajax({
url: '/where/to/post',
type: 'POST',
data: {"id": 10},
processData: false
});
Usually, jQuery converts anything in data to query string format like id=10. The processData flag tells jQuery to interpret it literally as a json hashmap.
Posting the JSON object will give me the string "id=10" on my service side.
Javascript does not do your this conversion, so your server does it.
It is likely that your server reacts differently based on the content-type of your POST e.g. application/json vs text/plain or text/html, a common feature of REST based services.
The answers here gave me a few hints, but ultimately, it was a lot of tweaking before it would work correctly. I had to do 3 things:
Add processData: false.
Turn the JSON object into a JSON string. The request wouldn't fire if I left it as an object (even if I changed contentType to application/json).
Change the contentType to text/plain. This sent it as a raw string.
And that's what did the trick. I now get the JSON string I want on the server side.