Produce Data in JSON - java

Need your help.
I am using postman and trying to get information in JSON format.
But instead of correct format of message i got this result -> "[]"
I don't have any error and i can print in console the requested information, but can't in the browser. I hope anybody can give me a clue..
#GET
#Path("/{messager_id}")
#Produces(MediaType.APPLICATION_JSON)
public String GetMessageById(#PathParam("messager_id") long id){
String message = new MessageService().getMessageById(id);
return message;
}

I would recommend to first of all, use some webservice client as DHC REST Client (an addon for Chrome browser). Use it and check the real behaviour of your webservice. If the client gets and empty json object, then sure your server is producing empty data. Log the string message to be sure is returning data. If it is correct, check the return method. An example of returning of a webservice can be:
return Response.ok(message, MediaType.APPLICATION_JSON).build();

Check if the content type header is set : Content-type = application/json. Please provide additional information.

One thing to check for is to ensure that the MessageService.getMessageById(id) is returning data.

Related

How to test Post Request in Postman for a DTO that contains file type

Sorry, but I wanted to confirm if there was a way to do this without having to serialize to JSON, which is what I kept on reading online.
The problem that I am having is that I want to test with Postman my email service which has a Email dto of
{
String toEmail
String subjectLine
String content
List<File> attachments (Text files can be used for test if that helps)
}
Previously, before adding the list of files, I could use Postman to test with raw under the body tab of postman and sending in a json. However, I don't think I can add an object with that same method. When trying out form-data though, I am getting that the request entity is in a format not supported.
Currently, my service is only taking in a EmailDto as its resource.
Does anyone have suggestions or thoughts?

Whats the best way to extract response body from com.amazonaws.Response to JSON string

I am sending the following Sig4 request:
Response response = new AmazonHttpClient(new ClientConfiguration())
.requestExecutionBuilder()
.executionContext(new ExecutionContext(true))
.request(request)
.errorResponseHandler(new AWSErrorResponseHandler(false))
.execute(new AWSResponseHandler(false));
I then convert the response to httpResponse: (not sure if its needed)
com.amazonaws.http.HttpResponse httpResponse = response.getHttpResponse();
My issue is that I was unable to find a simple explanation on how to extract the actual JSON response
string out of my response.
EDIT: Note that when I follow the SDK doc and try to extract the content as an input stream:
IOUtils.toString(response.getHttpResponse().getContent());
I get the following exception:
java.io.IOException: Attempted read from closed stream.
at org.apache.http.impl.io.ContentLengthInputStream.read(ContentLengthInputStream.java:165)
at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:135)
at com.amazonaws.internal.SdkFilterInputStream.read(SdkFilterInputStream.java:90)
at com.amazonaws.event.ProgressInputStream.read(ProgressInputStream.java:180)
at java.base/java.io.FilterInputStream.read(FilterInputStream.java:106)
at com.amazonaws.util.IOUtils.toByteArray(IOUtils.java:44)
at com.amazonaws.util.IOUtils.toString(IOUtils.java:58)
Any assistant would be highly appreciated :)
For HTTP responses I used RestAssured. With this it should work like this:
Response response = new AmazonHttpClient().execute() // build and run your query
String json = response.getBody().prettyPrint();
If you want to use the information of the json directly afterwards within the code I can recommend creating a POJO and then doing the following:
AmazonResponseDto dto = response.as(AmazonResponseDto.class)
A quick look up of the com.amazonaws.http.HttpResponse docs showed me, that you can get an InputStream from it, but not directly a json.
I don't know the package of the Response you used in your first code block, that's why I recommended RestAssured.
I found the reason for my issue. As some have suggested, the response is an input stream, yet when I tried to extract it to starting I either got a closed connection exception or nothing. To fix this I had to change .execute(new AWSResponseHandler(true)); to true instead of false in order to keep the connection open. AWSResponseHandler implements HttpResponseHandler and sets the following:
public AWSResponseHandler(boolean connectionLeftOpen) {
this.needsConnectionLeftOpen = connectionLeftOpen;
}
I hope this helps anyone who gets into a similar situation.

GET parameter being received on server without quotes

I am working on a web application where on clicking a button on the UI a GET request is made to the server as below:
https://mywebapp.com?info=%5B%7B%22first%22%3A%22abcd%22%2C%22second%22%3A%22efgh%20ijkl%22%2C%22third%22%3A%22mnop%22%7D%5D
Basically the value I am passing as info is:
[{"first":"abcd","second":"efgh ijkl","third":"mnop"}]
However, when I read this passed value on server, I found it to be received as:
[{first:abcd,second:efgh ijkl,third:mnop}] i.e. all the double quotes are removed.
Now when I try to parse it into json, it fails.
Could you please suggest how could I fix the issue so that the json is received as expected.
Please note that it is an existing big application and I can't change any server level settings.
Thanks
To keep the double qoutes as is you have to send the json in single qoutes
i,e convert the json into string then send it, because the GET/POST request don't recognize json format

need to pass some content in header in get request of JSON using restTemplate

I need to consume the rest service using my rest client.
From the 1st URL, need to fetch some content (in this case it is a JSON web token).
And in the 2nd URL, need to pass this token in request header. Please help me achieving the same.
Just to note, the 1st URL is with POST and whereas the second URL is with GET request.
With the help of RestTemplate api, I am able to get the response body and response header when passing the first URL in method PostForObject(url, map, String.class). From Response header, I am able to get the details about pragma, cache, content-type, server, content-length, expires etc but not able to fetch the JWT string (Json Web Token). I need to get the JWT as I need to pass this into the request header of 2nd URL (GET) to get the actual information.
You can make use of Path Params to fetch data from the URL and use the same to add to a different URL-
Example:
#Path("/{taskId}")
public Task get(#PathParam("taskId") Long taskId)
{
// Handles GET on /tasks/{taskId}. Returns a single task for the given taskId.
return taskService.find(taskId);
}
for more details visit : http://java.dzone.com/articles/spring-3-webmvc-optional-path
If this helps you, mark as answer
I could get this info, I am posting the same as below in case someone needs the same.
Collection<List<String>> headerContent = restTemplate.postForEntity(URI url,
Object request, Class<T> responseType),getHeaders().values();

java - JsonMessage is ok in server side but returns error 500 to client

I do a ajax call to get a list of items but it returns HTTP error 500.
I traced it in server and map is populated without error. No exception is thrown.
#ResponseBody
#RequestMapping(value = "some/path", method = RequestMethod.POST )
public JsonMessage getlist(#RequestParam(value = "id") Long id){
MyObject myobject = myObjectManager.get(id);
Map map = new HashMap<>();
map.put("shits",lottery.getMultipleRewards());
return JsonMessage.Success(map);
}
any ideas?
(If the map is empty or I set something static like a string on it then it works).
I've seen this happening with particularly demanding implementations when the client didn't include the proper Accept: application/json header or the server didn't include the Content-Type: application/json.
Since the error occurs outside of your code the logging might be generated in an unexpected way/place and you might have suppressed that particular logger.
Another thing that I can think of is that you might be proxy-ing the request through another server. In this case the server that handles the request can generate a correct response but the proxy throws an error for some reason.
Try return a string
if works try simplest object(with xml root)
if it works try to return single object without root.
if it works try map of strings
check if all loggers are set correctly.
Your configuration and used technology might be helpful in diagnose.

Categories

Resources