我们目前正在使用Web-flux将一些旧服务重写为spring框架。由于传统逻辑允许在GET请求上接收有效负载或多部分数据,因此我们需要在新服务中重新创建该行为。
如果发生Get请求,Web-flux不允许我们接收有效负载或多部分数据。我在@RestController和@Controller中测试了此行为。是否可以更改web-flux的配置以处理此类情况?
UploadFileController的示例:
@Controller
public class UploadController {
@GetMapping(value = "/upload")
public @ResponseBody Mono<ResponseEntity<String>> upload(@RequestBody Flux<Part> parts) {
System.out.println("Upload controller was invoked");
return parts.next()
.flatMap(part -> DataBufferUtils.join(part.content()))
.map(this::mapDataBufferToByteArray)
.map(data -> {
String uploadedData = new String(data);
System.out.println("Uploaded file data: " + uploadedData);
return ResponseEntity.ok(uploadedData);
});
}
private byte[] mapDataBufferToByteArray(DataBuffer buffer) {
byte[] data = new byte[buffer.readableByteCount()];
buffer.read(data);
return data;
}
}
public class UploadControllerTest {
@Autowired
private TestRestTemplate testRestTemplate;
@Test
public void shouldUpload() {
// given
final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
LinkedMultiValueMap<String, Object> parameters = new
LinkedMultiValueMap<>();
parameters.add("file", "Test");
// when
ResponseEntity<String> response =
testRestTemplate.exchange("/upload",
HttpMethod.GET,
new HttpEntity<>(parameters, httpHeaders),
String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
}
问题来源:Stack Overflow
如何创建将内部传入的get请求转换为post的webfilter呢?
@RestController
public static class GetPostHandler {
@PostMapping("/test")
public Flux<String> getName(@RequestPart("test") String test, @RequestPart("test2") String test2) {
return Flux.just(test,test2);
}
}
@Component
public class GetPostFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange serverWebExchange,
WebFilterChain webFilterChain) {
ServerHttpRequest req = serverWebExchange.getRequest().mutate().method(HttpMethod.POST).build();
return webFilterChain.filter( serverWebExchange.mutate().request(req).build());
}
}
我测试过
curl -X GET \
http://localhost:8080/test \
-H 'cache-control: no-cache' \
-H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
-F test=1 \
-F test2=2
结果是正确的:
回答来源:Stack Overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。