Is there a way to find out if ServerRequest has a body? - spring-webflux

I would like to check wether ServerRequest contains body.
Is there a way to find out that beforehand calling bodyToMono method?

Assuming that clients do send corresponding headers, you can achieve it by checking the content-length header like this:
request.headers().contentLength().orElseGet(0) > 0
You can have it in the Handlers directly, or in a Filter as well

You can use .body(BodyExtracter) method in Server request instance
To convert to a Mono<Boolean> which has true value if the body contains data, use
Mono<Boolean> bodyContains = request.body((serverHttpRequest, context) -> serverHttpRequest
.getBody()
.collectList()
.map(List::isEmpty));

Related

How to send custom http response code back from spring cloud functions in gcp?

We are using the new gcp cloud functions using Java / Kotlin.
As in the current reference implementations, we are returning org.springframework.messaging.support.GenericMessage objects.
So our code looks like this (Kotlin):
fun generatePdfInBase64(message: Message<Map<String, Any>>): Message<*> {
val document = process(message)
val encoded = Base64.getEncoder().encodeToString(document.document)
return GenericMessage(encoded)
}
We were not able to find any way to include a custom http response code to our message, e.g. 201 or something. The function only responds 200 in case of no exception or 500.
Does someone know of a way to do this?
Best wishes
Andy
As it is mentioned at the official documentation, the HttpResponse class has a method called setStatusCode where you are able to set the number of the status as your convenience
For example:
switch (request.getMethod()) {
case "GET":
response.setStatusCode(HttpURLConnection.HTTP_OK);
writer.write("Hello world!");
break;
On the other hand the constructor of the GenericMessage receives as parameter a payload, therefore I think you can create a string with a json format and use the constructor for create your GenericMessage instance with the status response you need.
If you want to know more about the statuds codes take a look at this document.

How to set http response code in Parse Server cloud function?

A parse server cloud function is defined via
Parse.Cloud.define("hello", function(request, response) {..});
on the response, I can call response.success(X) and response.error(Y), and that sets the http response code and the body of the response.
But how do I define a different code, like created (201)?
And how do I set the headers of the response?
thanks, Tim
You are allowed to return any valid JSON from response.success(). Therefore, you could create an object with fields such as code, message, and value, so you can set the code, give it a string descriptor, and pass back the value you normally would, if there is one. This seems to accomplish what you need, though you will have to keep track of those codes across your platforms. I recommend looking up standard http response codes and make sure you don't overlap with any standards.

Add http header in HTTPFound() with pyramid

I have a Pyramid application where I have the following line of code:
return HTTPFound(location=request.route_url('feeds'))
However I want to pass an extra parameter in the headers. Im trying with this:
headers = {"MyVariable": "MyValue"}
return HTTPFound(location=request.route_url('feeds'),headers=headers)
However the view_config of "feeds" does not get MyVariable in the headers. I'm checking it with the following code:
print "**************"
for key in request.headers.keys():
print key
print "**************"
What am I doing wrong?
headers is meant to be a sequence of (key, value) pairs:
headers = [("MyVariable", "MyValue")]
This lets you specify a header more than once. Also see the Response documentation, the headers keyword is passed on as headerlist to the Response object produced. Also see the HTTP Exceptions documentation:
headers:
a list of (k,v) header pairs
However, headers are only sent to the client; they are not passed on by the client to the next request that they are instructed to make. Use GET query parameters if you need to pass information along to the redirection target, or set values in cookies or in the session instead.
To add on query parameters, specify a _query directory for route_url():
params = {"MyVariable": "MyValue"}
return HTTPFound(location=request.route_url('feeds', _query=params))
and look for those query parameters in request.GET:
for key in request.GET:
print key, request.GET.getall(key)
Due to the way HTTP works, what you are asking is not possible. You can use either GET parameters to pass the data, or you can store the data in a cookie instead.

How to set response headers with Rikulo Stream server?

I have one API that returns information in JSON, and for that, I would indicate that the content-type of the HttpResponse is application/json.
So, with Rikulo, I have something like :
connect.response.headers.set(HttpHeaders.CONTENT_TYPE, contentTypes['json']);
But when I request my API, it told me that the headers are immutable.
HttpException: HTTP headers are not mutable
#0 _HttpHeaders._checkMutable (http_headers.dart:267:21)
#1 _HttpHeaders.set (http_headers.dart:31:18)
Therefore, how can I set my response headers, or there is a native solution with Rikulo to return JSON data ?
You can set the contentType property directly:
connect.response.headers.contentType = contentTypes["json"];
If you'd like to set the header instead, you have to pass a String object (which Dart SDK expects):
connect.response.headers.set(HttpHeaders.CONTENT_TYPE,
contentTypes['json'].toString());
But the error message shall not be as you posted. Like Kai suggested in the comment, the message indicates you have output some data before setting the header.

wcf message response parameter

I've read this example http://msdn.microsoft.com/en-us/library/ee476510.aspx about dynamic responses in wcf.
The sample on the bottom fit my goal pretty well. This is what i did:
[OperationContract]
[WebGet(UriTemplate = "/salaries({queryString})")]
Message GetSalaryByQuery(string queryString);
and my GetSalaryByQuery-Method:
public Message GetSalaryByQuery(string querystring)
{
if (WebOperationContext.Current.IncomingRequest.Accept == "application/json")
return WebOperationContext.Current.CreateJsonResponse<Result>(Salary.GetSalaryByQueryJson(querystring));
else
return WebOperationContext.Current.CreateAtom10Response(Salary.GetSalaryByQuery(querystring));
}
It is pretty similiar to the example i found.
But its not working however. It says that there is another parameter besides the message. I googled the message-class and it seems to me that its not possible to add an parameter to a message-response.
Is there a way to pass a parameter with the request and get a response with a message object?
Is there another way to get the dynamic response?
Thanks in advance.
I got it to work. I just deleted the Metadata-Enpoint and the behavior. My Webservice provides metadata on its own and therefore doesnt need to have the mex-Metadata defined.