I've been working with Spring Boot 2.0.0.RC1
and use spring-boot-starter-webflux
in order to build a REST Controller that returns a flux of text data.
@GetMapping(value = "/")
public Flux<String> getData(){
return Flux.interval(Duration.ofSeconds(2))
.map(l -> "Some text with umlauts (e.g. ä, ö, ü)...");
}
Since the text data contains some umlauts (eg ä, ö, ü), I would like to change the Content-Type header of the response from text/event-stream
to text/event-stream;charset=UTF-8
. Therefore, I tried wrapping to flux into a ResponseEntity
. Like this:
@GetMapping(value = "/")
public ResponseEntity<Flux<String>> getData(){
return ResponseEntity
.ok()
.contentType(MediaType.parseMediaType("text/event-stream;charset=UTF-8"))
.body(Flux.interval(Duration.ofSeconds(2))
.map(l -> "Some text with umlauts (e.g. ä, ö, ü)..."));
}
Now, making a curl request to the endpoint shows that the Content-Type remains the same:
< HTTP/1.1 200 OK
< transfer-encoding: chunked
< Content-Type: text/event-stream
<
data:Some text with umlauts (e.g. ├ñ, ├Â, ├╝)...
I suspected the MediaType.parseMediaType()
method to be the issue, but the media type is parsed correctly (as this screenshot shows):
However, the parameter charset
seems to be ignored. How can I change the encoding to UTF-8 so that the browser interprets the umlaut characters correctly?
EDIT: Setting within the GetMapping
annotation the produces
field does not work either.
@GetMapping(value = "/", produces = "text/event-stream;charset=UTF-8")
public ResponseEntity<Flux<String>> getData(){
return ResponseEntity
.accepted()
.contentType(MediaType.parseMediaType("text/event-stream;charset=UTF-8"))
.body(Flux.interval(Duration.ofSeconds(2))
.map(l -> "Some text with umlauts (e.g. ä, ö, ü)..."));
}
You can create a Filter and process response before this return to browser
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.core.Ordered;
// esse filtro foi criado pra converter para UTF-8 o response do Flux<ServerSentEvent<String>>
// this filter was created to convert all responses to UTF8, including Flux<ServerSentEvent<String>>
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class FluxPreProcessorFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.