PUT response code with 204 - java

My PUT and POST are same, so I am using PUT operation. Here I need to send response body data when PUT successful e.g. either new data insert into Cassandra or update existing record.
So, what response code should I use in this case.. code 204 I am using for successful PUT with response body, but it automatic convert into 200 code while testing with POSTMAN. so what should I use here.

According to this:
If the target resource does not have a current representation and the
PUT successfully creates one, then the origin server MUST inform the
user agent by sending a 201 (Created) response. If the target
resource does have a current representation and that representation is
successfully modified in accordance with the state of the enclosed
representation, then the origin server MUST send either a 200 (OK) or
a 204 (No Content) response to indicate successful completion of the
request.
Based on this (and agreeing with Hank), if you have an entity with your response, you should use 201.

Related

How to make REST call asynchronous in Java

I have REST calls between two microservices, one of the call is taking more than 15 mins of time to complete. We have company's own private cloud implementation which is terminating any open connection kept for more than 15 mins.
We are looking for some asynchronous rest call implementation, where service A will trigger the rest call to service B and forget and service B will notify when the response is ready to be served.
Is there any widely used technique/API for such scenario? I was not able to find any thing concrete on this front.
You could use Polling. Something like this :
Service A triggers a Rest call to Service B which returns an OK response. Then in each 1 minute service A make another API request to another endpoint in Service B which would return status of the previous request until the process is completed or for may be a certain point of time. Now when the 2nd request send the status as success you can mark the process as completed.
Instead of creating the actual resources, create a temporary one. Instead of returning a 201 (Created) HTTP response, you can issue a 202 (Accepted) response code. This informs the client that the request has been accepted and understood by the server, but the resource is not (yet) created. Send the temporary resource inside the Location header.
Request:
POST /blogs HTTP/1.1
<xml>
blogdata
</xml>
Response:
HTTP/1.1 202 Accepted
Location: /queue/12345
This location can store information about the status of the actual resource: an ETA on when it will be created, what is currently being done or processed.
When the actual resource has been created, the temporary resources can return a 303 (See other) response. The location header returns the URI to the definitive resource. A client can either DELETE the temporary resource, or the server can expire this resource and return a 410 (Gone) later on.
Source: https://restcookbook.com/Resources/asynchroneous-operations/

HTTP: what is the correct way to send "retry/redirect" response

I need to force the client to retry its request (meaning to send the same request one more time). What I'm thinking of is a response with status-code 307 and header Location: <original-url> (that's good enough for now, unless there's a better way).
My question is, from HTTP specification point of view, what is the correct value for Location in this specific context. Or more specifically in Java having request of type HttpServletRequest, which one should I use: getRequestURI (Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request) or getRequestURL (Reconstructs the URL the client used to make the request containing protocol, server name, port number, and server path, but it does not include query string parameters).
Any other suggestion/comment is appreciated.
getRequestURL() returns complete URL used by the client where as getRequestURI() returns just the basic path resides in server.
i am using this technique to redirect with a response status this is my code this is useful:-
httpServletResponse.reset();
httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
httpServletResponse.setHeader("SERVER-RESPONSE", "bad request");
return;
and also you can set headers in response.
I believe a redirect is the wrong status code in the first place.
Isn't this what 503 is for? (https://www.greenbytes.de/tech/webdav/rfc7231.html#status.503)

FormData getting lost in HTTP 302 to 200

We getting a SSO request using Ping Identity Federation server which opening target URL with a post of opentoken as form data. But at my application I am getting two request one is 302 Found where I can see form data in headers but after that it issue a 200 request in which data is not there.
Is this normal if yes how to get formdata?
Just curious for this behaviour....I can still access that data from referrer header information.
I am using java/jsp.
It was actually coming in request body which need to be read using getReader. that's why it redirecting again to 200 as in first request I was consuming parameter instead of body.

Get response header OkHttp

I need to check response header of HTTP request using OkHTTP library. before loading data I need to check it's last update time. The problem in that that the response body is about 2 MB so I need to get only Last-Modified header. Is it possible to load only response header without response body to increase the speed of the program`s RESTful actions?
You can send a HTTP HEAD request which only retrieves the headers. You only need to check if your server application supports HEAD requests.
The HEAD method is identical to GET except that the server MUST NOT
return a message-body in the response. The metainformation contained
in the HTTP headers in response to a HEAD request SHOULD be identical
to the information sent in response to a GET request. This method can
be used for obtaining metainformation about the entity implied by the
request without transferring the entity-body itself. This method is
often used for testing hypertext links for validity, accessibility,
and recent modification. (http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html)
Example for OkHttp:
String url = ...
Request request = new Request.Builder().url(url).head().build();
The response body is streamed, so you can make the regular request, read the headers, and then decide whether or not to consume the body. If you don’t want the body, you can close() it without much waste.
There is a slight cost to the server to serve a response that might be abandoned. But the overall cost will be lower than making a HEAD and then a GET request unless you expect abandon a significant fraction (say > 90%) of requests.

Jersey 'NoContent' response returns 200 instead of 204

I am using Jersey (1.18) to build a REST API for my WebApplication. In a part of my code I have the following snippet.
return Response.status(Status.NO_CONTENT).entity(err_message).build();
where Status is an instance of com.sun.jersey.api.client.ClientResponse.Status;
According to Jersey Documentation NO_CONTENT should return a 204 code, instead of this, the http response has a header with 200 code.
NO_CONTENT
public static final ClientResponse.Status NO_CONTENT
204 No Content, see HTTP/1.1 documentation.
I tried to change the aforementioned code to
return Response.noContent().entity(err_message).build();
But the issue still exists.
As a side note, using NOT_FOUND instead of NO_CONTENT, return a 404 header as expected.
Any suggestion on 'How can I return 204 code?', is this a bug or I am doing something wrong.
Note: Not a duplicate of Returning 200 response code instead of 204
See this SO answer which says,
...204 means "No Content", meaning that the response contains no
entity, but you put one in it. It's likely that Jersey is switching it
to a 200 for you, which is basically identical to a 204 except that it
contains a response entity.
Finally, you can get 204 responses very simply by a couple of built-in
behaviors: void methods and null return values both map to a 204
response. Otherwise, simply return Response.status(204).build().
In other words, if you want "NO_CONTENT" then don't include content in your response.
After a little more digging I have found the problem. The W3c Documentation gives a hint.
I am quoting
10.2.5 204 No Content
The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.
If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent's active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent's active view.
The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.
In my code I have entity(err_message) which causes the problem. By removing it the 204 is returned correctly. I think somehow the Jersey or 'someone' casts the response to 200 since it has content.
Update (02/05/2015)
This blog post link (posted earlier today as an answer and then deleted), gives some additional insights about situation. Based on the content of the blog post, whenever there is any content in the HTTP response the following method is invoked. This method sets the status code back to 200.
private void commitWrite() throws IOException {
if (!isCommitted) {
if (getStatus() == 204)
setStatus(200);
   isCommitted = true;
   o = responseWriter.writeStatusAndHeaders(size, ContainerResponse.this);
}
}
We can say that Jersey detects that since there is some content in the response, the status code was wrongly set to 204 and it changes it to the appropriate 200.

Categories