Set Response Status Code

Set Response Status Code

PHP <=5.3

The header() function has a parameter for status code. If you specify it, the server will take care of it from there.

header('HTTP/1.1 401 Unauthorized', true, 401);

PHP >=5.4

See Gajus' answer: https://stackoverflow.com/a/14223222/362536

How to set response status code in Filter when controller returns ResponseEntity?

With the /string endpoint, you're not modifying the status code. With the /entity endpoint, you explicitly are (you're setting it to 200 by virtue of returning an ok).

Your filter implementation changes the response status code and then proceeds to run the rest of the filter chain -- and then the servlet. And we just established the servlet (your controller) is setting the response status code to something else.

So you need to change the response code after the servlet/controller has done its thing.

Your first thought might be to reimplement your filter like this:

@Component
public class TestFilter implements Filter {

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
try {
chain.doFilter(req, resp);
} finally {
HttpServletResponse response = (HttpServletResponse) resp;

response.setStatus(205);
}
}
}

But unfortunately, that won't work either! According to the documentation:

Note that postHandle is less useful with @ResponseBody and
ResponseEntity methods for which the response is written and committed
within the HandlerAdapter and before postHandle. That means it is too
late to make any changes to the response, such as adding an extra
header. For such scenarios, you can implement ResponseBodyAdvice and
either declare it as an Controller Advice bean or configure it
directly on RequestMappingHandlerAdapter.

This might have the desired effect you're looking for (note I set to "CHECKPOINT" just to demonstrate the point!):

@ControllerAdvice
public class TestResponseBodyAdvice<T> implements ResponseBodyAdvice<T> {

@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}

@Override
public T beforeBodyWrite(T body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
//
// insert status code of choice here
response.setStatusCode(HttpStatus.CHECKPOINT);

return body;
}

}

How to set http status code when responding to servlet client from Filter class-method in tomcat

I've implemented a filter for authentication shortly. I've coded something similar to this:

public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain)
{
HttpServletResponse response=(HttpServletResponse) resp;

boolean authenticated=false;
// perform authentication

if (authenticated)
{
chain.doFilter(req, response);
}
else
{
// don't continue the chain
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "BASIC realm=\"Your realm\"");

response.setContentType("what you need");
PrintWriter writer=response.getWriter();

// don't set content length , don't close
}
}

How to set response status code in route with type json in odoo 14

You cannot specify the code of the response, as you can see the status code is hardcoded in http.py:

def _json_response(self, result=None, error=None):

# ......
# ......

return Response(
body, status=error and error.pop('http_status', 200) or 200,
headers=[('Content-Type', mime), ('Content-Length', len(body))]
)

If the result is not an error the status code is always 200. but you can change the code of the method directly or use a monkey patch witch if it's not really important to specify the code of status in the result don't do ti ^^.

A simple monkey patch put this in __init__.py of the module that you want this behavior in it.

from odoo.http import JsonRequest

class JsonRequestPatch(JsonRequest):

def _json_response(self, result=None, error=None):
response = {
'jsonrpc': '2.0',
'id': self.jsonrequest.get('id')
}
default_code = 200
if error is not None:
response['error'] = error
if result is not None:
response['result'] = result
# you don't want to remove some key of another result by mistake
if isinstance(response, dict)
defautl_code = response.pop('very_very_rare_key_here', default_code)

mime = 'application/json'
body = json.dumps(response, default=date_utils.json_default)

return Response(
body, status=error and error.pop('http_status', defautl_code ) or defautl_code,
headers=[('Content-Type', mime), ('Content-Length', len(body))]
)


JsonRequest._json_response = JsonRequestPatch._json_response

and in the result of JSON api you can change the code of status like this

 def some_controler(self, **kwargs):
result = ......
result['very_very_rare_key_here'] = 401
return result

The risk in monkey patching is you override the method compeletly and if some change is done in Odoo in new version you have to do you it in your method too.
The above code is from odoo 13.0 I did a lot of this when I build a restfull module to work with a website uses axios witch don't allow sending body in GET request. and odoo expect the argument to be inside the body in json request.

Laravel - How to set HTTP response status code from Controller

Solution

You could use what is mentioned here. You will need to return a response like this one:

public function index()
{
$data = ['your', 'data'];

return response()->view('layouts.default', $data)->setStatusCode(404);
} // ^^^^^^^^^^^^^^^^^^^

Notice the setStatusCode($integer) method.

Alternative

You could set an additional header when returning the view to specify additional data, as the documentation states:

Attaching Headers To Responses


Keep in mind that most response methods
are chainable, allowing for the fluent construction of response
instances. For example, you may use the header method to add a series
of headers to the response before sending it back to the user:

return response($content)
->header('Content-Type', $type)
->header('X-Header-One', 'Header Value')
->header('X-Header-Two', 'Header Value');

How can I set response status code when using `RoutingContext::json` method?

You can use Kotlin apply for that:

it.apply {
response().statusCode = 409
json(jsonObjectOf("error" to "EmailAlreadyInUse"))
}

How to set HTTP Status code reason with Apache Camel REST DSL (Servlet/Restlet)

How can I configure Camel/Restlet/Servlet to include the reason on the HTTP Status code?

Without a custom core, I believe you can't:

The response is being sent at org.restlet.engine.adapter.ServerCall.sendResponse(), where the response head and body are written to the OutputStream:

writeResponseHead(response); // <--
if (responseEntity != null) {
responseEntityStream = getResponseEntityStream();
writeResponseBody(responseEntity, responseEntityStream);
}

... and writeResponseHead(response) does nothing by default, check it:

protected void writeResponseHead(Response response) throws IOException {
// Do nothing by default
}

Update: ... the HttpStatus(value, reasonPhrase) has the reasonPhrase, but isn't used to stringify:

HttpStatus(int value, String reasonPhrase) {
this.value = value;
this.reasonPhrase = reasonPhrase;
}
...
@Override
public String toString() {
return Integer.toString(this.value);
}

Update 2: ... the DefaultRestletBinding.populateRestletResponseFromExchange does the following:

// get response code
Integer responseCode = out.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
if (responseCode != null) {
response.setStatus(Status.valueOf(responseCode));
}

... it only uses the Status.valueOf.

Although there is a Status.reasonPhrase, it isn't accessible.



Answer:

Without custom core, (I believe) you can't!



... what isn't inappropriate, given that:

  • RFC 2616 - Hypertext Transfer Protocol -- HTTP/1.1:

6.1.1 Status Code and Reason Phrase

(...) The client is not required to examine or display the Reason-Phrase.

(...) The reason phrases (...) MAY be replaced by local equivalents without affecting the protocol.

  • RFC 7230 - Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing:

3.1.2. Status Line

(...) A client SHOULD ignore the reason-phrase content.

  • RFC 7540 - Hypertext Transfer Protocol Version 2 (HTTP/2):

8.1.2.4. Response Pseudo-Header Fields

(...) HTTP/2 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line.

Need to know the meaning of a status code?

See the complete list of status codes maintained by IANA.



Related Topics



Leave a reply



Submit