getting parameters from httppost in android to grails - json

I am using the following code to convert json to StringEntity
StringEntity se = new StringEntity(json,"UTF-8");
se.setContentType("application/json");
httpPost.setEntity(se);
at the server side. i am using grails. I am unable to parse the data.
Say i have a controller : http://example.com/login
and login have following definition.
def login(params){
String email = params.email;
//validaton logic
}
it is unable to get the 'email' from post request. please anyone can guide me how to get the values.
I am passing two values in json objec i.e. email and password.

You should use request.JSON.email since it's a JSON request.

Related

Text Response from Spring REST API endpoint, how to retrieve that on Angular Front end

Spring REST API is responding with following response:
On successful execution : It returns me a response of Text type.
On unsuccessful execution : It returns me JSON error object.
Front-End Service Class :
private detailsURL = 'http://localhost:8080/register';
constructor(private http:HttpClient){}
register(regisDetails): Observable<any>{
return this.http.post(this.detailsURL,regisDetails);
}
Front-End Component Class:
registerUser(){
this.service.register(this.regisForm.value).subscribe(
success => this.successMessage = success,
error => this.errorMessage = error.error.errorMessage
);
}
In case of error I'm getting the error message I'm supposed to get. But in case of success I'm not getting the successMessage.
Just wanted to know if there's any way to fetch the Text type response on front end. Or else I'll have to change my backend to send response of JSON Type for successful execution as well.
Please help me understand this thing.
You have to set the status for your response. In the controller part you have to mention consumes="application/json" in api request.
You should be doing your changes at the backend and provide the response in Json format response for both the success and backend. That would be the ideal solution.
It is really a bad design to provide a different response than what is expected. You could check the value of the header in request "accept:application/json" and provide response as was expected by the front end
Front End Fix :
However, in the front end you could always use
JSON.parse(success) to convert the text to Json object and use it further as required.

Spring WebClient not processing JSON content

I have an app that uses WebClient to fetch JSON data from ComicVine as follows:
WebClient client = WebClient.builder()
.baseUrl(url)
.defaultHeaders(
headers -> {
headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
headers.add(HttpHeaders.USER_AGENT, "ComiXed/0.7");
})
.build();
Mono<ComicVineIssuesQueryResponse> request =
client
.get()
.uri(url)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(ComicVineIssuesQueryResponse.class);
ComicVineIssuesQueryResponse response = request.block();
For a time this worked. But then, all of a sudden, it's throwing the following root exception when it executes:
Caused by: org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/json' not supported for bodyType=org.comixed.scrapers.comicvine.model.ComicVineIssuesQueryResponse
at org.springframework.web.reactive.function.BodyExtractors.lambda$readWithMessageReaders$12(BodyExtractors.java:201)
I'm not sure why it all of a sudden won't process JSON data. My unit test, which is explicitly returning JSON data and setting the content type properly:
private MockWebServer comicVineServer;
this.comicVineServer.enqueue(
new MockResponse()
.setBody(TEST_GOOD_BODY)
.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE));
Any ideas why this is the case? It's happening across multiple classes that use this same setup for WebClient and for testing.
After doing some digging, I added the following code to get the JSON as a String and then use ObjectMapper to convert it to the target type:
Mono<String> request =
client
.get()
.uri(url)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(String.class);
String value = request.block();
ObjectMapper mapper = new ObjectMapper();
ComicVineIssuesQueryResponse response = mapper.readValue(value, ComicVineIssuesQueryResponse.class);
This quickly exposed the underlying problem, which was that two instance variables in the response were annotated with the same JSON field name. Once I fixed that, things started working correctly again.
you can parse the json content to string without calling block method.
option 1) Jackson2Tokenizer
option 2) put your code which is calling "objectMapper.readValue(..) .." inside map operator.

SoapUI REST + JSON Mock Service: How can I return data from the request in a response?

I have a SoapUI REST (i.e. non-SOAP) mock service that returns a response for a POST request.
The request and response both contain JSON content.
At the moment, I can get it to return a static response and that works fine, but I want some of the values in the response to be dynamically sourced from the request.
So if I have this request:
{
"the_request":{
"abc":"123",
}
How can I get the value of "abc" copied in the response?
Investigation has lead me to believe I can do this via including a variable in the response, something like:
Response:
{
"the_response":{
"value_from_request":"${#MockResponse#Request#the_request#abc}",
"other":"stuff",
}
And then implementing a script to populate the variable in the response, via the Script tab.
How can I then populate this with data from the request?
Currently SoapUI just generates an empty value
"value_from_request":"",
Tried using mockRequest.requestContent in the Script tab, but have not found how to obtain the "123" value from it.
OK, worked this out. So the response message can simply reference a variable in the requestContext like so:
Response:
{
"the_response":{
"value_from_request":"${the_value}",
"other":"stuff",
}
And a groovy script can be used to parse the JSON request content and populate "the_value" or whatever you like in the requestContext:
// Parse the JSON request.
def requestBody = new groovy.json.JsonSlurper().parseText(mockRequest.getRequestContent())
// Set up "the_value" from the request message.
requestContext.the_value = requestBody.the_request.abc
// Bit of logging so can see this in the "script log" tab.
log.info "Value extracted from request: ${requestContext.the_value}"
I think the script should be like this
def requestBody = new groovy.json.JsonSlurper().parseText(mockRequest.getRequestContent())
context.setProperty("the_value",requestBody.the_request.abc)

Send both JSON response and model in Grails

I'm new to Grails and I'm stuck up with a problem. I want to know if there is a way to send both JSON and view and model through "render" in Grails.
I'm using a jQuery Datatable to display data returned from server which is read from JSON returned by the controller. I also need to display error messages on the same view in case of validation failure in form fields. But I'm able to return either only the JSON or model and view using render. I also tried sending the JSON through model itself but it didn't work.
This is my code:-
def hierarchyBreakInstance = new HierarchyBreak(params);
String json = "{\"sEcho\":\"1\",\"iTotalRecords\":0,\"iTotalDisplayRecords\":0,\"aaData\":[]}";
hierarchyBreakInstance.errors.reject(message(code: 'hierarchyBreak.error.division.blank'));
render(view: "hierarchyBreak", model: [hierarchyBreakInstance: hierarchyBreakInstance]);
//render json;
The gsp code:-
<g:hasErrors bean="${hierarchyBreakInstance}">
<div class="errorMessage" role="alert">
<g:eachError bean="${hierarchyBreakInstance}" var="error">
<g:if test="${error in org.springframework.validation.FieldError}" > data-field-id="${error.field}"</g:if>
<g:message error="${error}"/>
</g:eachError>
</div>
</g:hasErrors>
Could you please let me know if there is a way to do this. Thanks!
You can use like this.
def hierarchyBreakInstance = new HierarchyBreak(params);
String json = "{\"sEcho\":\"1\",\"iTotalRecords\":0,\"iTotalDisplayRecords\":0,\"aaData\":[]}";
hierarchyBreakInstance.errors.reject(message(code: 'hierarchyBreak.error.division.blank'));
render(view: "hierarchyBreak", model: [hierarchyBreakInstance: hierarchyBreakInstance,json:json]);
//render json;
Assuming that you are doing a request with some parameters, and need to return if was succesfull or not, and the data to fill the table with ajax.
I will do on that way, use the statuses of the HTTP to mark if it was a problem with the validation(normally we return 400 Bad Request and the message)
Example :
return ErrorSender.sendBadRequest("error validating field $field with value $value")
And the errorsender has a sendBadRequest method
[response: ['message': message, error: "bad_request", status: 400, cause: []], status: 400]
If the request was OK, you only need to respond the data with something like
return [response: results, status: 200]
In the client side you have to have one function if the request was OK to parse result, and one function if request have some validated data problem, database problem or whatever that caused that the request didnĀ“t return a 200(in the example),there are more status codes, you can check on
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
PD: Initial validation should be done on client side.

No MediaTypeFormatter error when trying to parse ReadAsFormDataAsync result in WebAPI

I have created a WebAPI project to help capture statements from a TinCan learning course but I am having extreme difficulty in retrieving any of the Request payload details. Within this payload I pass the whole statement that I am trying to capture but upon trying to read using:
var test = Request.Content.ReadAsFormDataAsync().Result.ToString();
I get the following error message:
No MediaTypeFormatter is available to read an object of type 'FormDataCollection' from content with media type 'application/json'.
I have tried Converting the result object to JSON to overcome this problem but it has not been any use. Do I need to configure json somewhere in the configuration? I have tried adding
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
and also:
var jsonFormatter = config.Formatters.JsonFormatter;
config.Formatters.Insert(0, jsonFormatter);
to my WebApiConfig.cs file as answered in another question of how to return json but I cannot seem to pass this error. I have also set config.formatter to accept application/json but this also has not worked
CONTROLLER CODE
public void Put([FromBody]string statementId)
{
var test = Request.Content.ReadAsFormDataAsync().Result;
System.Diagnostics.EventLog.WriteEntry("Application", "/xAPI/PUT has been called", System.Diagnostics.EventLogEntryType.Error);
}
From the error message you have provided, it seems like request content is in application/json. ReadAsFormDataAsync() can only read content of type application/x-www-form-urlencoded.
In this case, you can use ReadAsAsync<> if you have the type you want to be deserialized defined or simply use ReadAsStringAsync<> if you just want to read the content as a string.