Is there any way to pass a Json status/response from Springboot to Angular service? Let’s say, beside the Httpstatus sent on Response Entity, I want also to send a Json response. Thanks
Or maybe a second question is how to use the Http status from Spring boot, in Angular service.
From your springboot endpoint, you can send JSON response along with the HttpStatus
Below is the sample code
#GetMapping(value = "/getUserDetails" , produces = "application/json")
public ResponseEntity getUserDetails(){
userDetails = userService.getUserDetails();
return ResponseEntity.status(HttpStatus.OK).body(userDetails);
}
This is how you can return userDetails object which will be converted to JSON automatically as we used produces = "application/json"
Related
I'm building my first WebAPI using ASP.NET MVC 4 WebAPI.
The requests must be sent using the application/json ContentType with utf-8 as the character set.
My POST method looks like this:
public HttpResponseMessage Post([FromBody]string value)
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
Whenever I'm sending a POST request the parameter 'value' is null. The request body contains Json: { "name":"test" }.
What I prefer is to have the parameter of the Post method to be either a string containing the Json or be of type JObject (from the JSON.NET library). How do I accomplish this? And is this even possible?
The easiest way is to grab the raw string directly from Request.Content:
public async Task<HttpResponseMessage> Post()
{
string value = await Request.Content.ReadAsStringAsync();
return new HttpResponseMessage(HttpStatusCode.OK);
}
There is a way to make ASP.NET Web Api treat your request body as string content, but in order to do that the content must be in =value format, in your case something like this:
={ "name":"test" }
You can achieve something like this with following jQuery code (for example):
$.post('api/values', '=' + JSON.stringify({ name: 'test' }));
In that case you can use signature from your question.
In the end there is always an option of creating your own MediaTypeFormatter to replace the default JsonMediaTypeFormatter and make it always deserialize the content into JObject. You can read more about creating and registering MediaTypeFormatter here and here.
I am attempting to build a REST service using Netty on the backend. I need to be able to post raw JSON to the service outside of any key/value parameters. Content-type=applicaiton/json not form multi-part.
I am able to get the initial part of the service to receive the request, but when I cast the MessageEvent content to HTTPRequest, it no longer has any posed data associated with it. That leaves me with no ability to get the JSON data back.
In order to access the posted JSON, do I need to use a different process for extracting the data from the MessageEvent?
Here is the snippet in question.
#Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
System.out.println("The message was received");
HttpRequest request = (HttpRequest) e.getMessage();
if (request.getMethod() != POST) {
sendError(ctx, METHOD_NOT_ALLOWED);
return;
}
// Validate that we have the correct URI and if so, then parse the incoming data.
final String path = sanitizeUri(request.getUri());
decoder = new HttpPostRequestDecoder(request);
System.out.println("We have the decoder for the request");
List<InterfaceHttpData> datas = decoder.getBodyHttpDatas();
for (InterfaceHttpData data : datas){
System.out.println(data.toString());
}
What am I missing that it causing this? Do I need to use the ChunkedWrite portion? I am a noob to Netty so forgive me if this is basic. I found lots of other questions about posting raw JSON to other URL's from inside Netty, but nothing about receiving it.
I've only used HttpPostRequestDecoder to read application/x-www-form-urlencoded or mime data.
Try just reading the data directly form the request as per the snoop example.
ChannelBuffer content = request.getContent();
if (content.readable()) {
String json = content.toString(CharsetUtil.UTF_8);
}
I have a rest-service which provides information in XML or JSON. I connect my application to this service with Spring Resttemplate. Unfortunately my responses are all in XML instead of the prefered JSON format. My analysis of the requests is, that Spring Resttemplate sends the request with the following Accept-Header:
Accept: application/xml, text/xml, application/*+xml, application/json
My rest-service response with the first accepted type. This is allways application/xml.
How can I change the Accept-Types so that I only get json responses? Are there some properties for this in the bean-definition of RestTemplate?
I use Spring 3.1 for this.
You need to set a list of HttpMessageConverters available to RestTemplate in order to override the default one:
RestTemplate rest = new RestTemplate();
rest.setMessageConverters(Arrays.asList(new MappingJacksonHttpMessageConverter()));
If you define RestTemplate in XML, do the same thing in XML syntax.
Not so clear from the topic if you want to consume JSON only or send.
In first case (consuming) you can annotate your Controller with
#RequestMapping(value="/path", headers = "Accept=application/json")
In case of producing you have to for ResponseEntry with contentType:
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", "application/json");
ResponseEntity.status(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.headers(headers);
i have a webservice which accepts 3 different types of object. i want to pass these objects using JSON........ and acccept the server side as JSON here i convert the objects into java objects.
can any one tell me the code.
My objects are Emploee, Student and cource.....
#POST
#Path("<some path here>")
public Response addBookJaxbJson(
#Multipart(value = "employee", type = "application/json") Employee emp,
#Multipart(value = "student", type = "application/json") Student student,
#Multipart(value = "course", type = "application/json") Course course)
throws Exception {
}
And of course, your client will have to send multipart data, either from a form or constructed somehow.
Firstly, my HTTP POST through a URL accepts 4 parameters. (Param1, Param2, Param3, Param4).
Can I pass the parameters from the database?
Once the URL is entered, the information returned will be in text format using JSON
format.
The JSON will return either {"Status" : "Yes"} or {"Status" : "No"}
How shall I do this in servlets? doPost()
Just set the proper content type and encoding and write the JSON string to the response accordingly.
String json = "{\"status\": \"Yes\"}";
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Instead of composing the JSON yourself, you may consider using an existing JSON library to ease the job of JSON (de)serializing in Java. For example Google Gson.
Map<String, String> result = new HashMap<String, String>();
result.put("status", "Yes");
// ... (put more if necessary)
String json = new Gson().toJson(result);
// ... (just write to response as above)
Jackson is another option for JSON object marshalling.