客户端正在发送已编码的有效负载(已编码的百分比),而给定的代码适用于未编码的有效负载/ XML(内容类型:application / xml),但它会失败,并会显示http 415的已编码的有效负载/ XML文件(内容类型:application / x-www-form-urlencoded)。

我注意到FormHttpMessageReader.java成功解码了有效负载(在调试日志中看到),但是在病房之后,请求流中的某个地方我的代码无法正确地将解码的XML映射到POJO。

卷曲请求-

curl -H 'Content-type: application/x-www-form-urlencoded' http://localhost:8081/api/v1/app/test  -d @encodedpyaload.xml -i-H 'Accept: application/xml, text/xml, application/x-www-form-urlencoded, */*’
HTTP/1.1 100 Continue

HTTP/1.1 415 Unsupported Media Type
Content-Type: application/json
Content-Length: 158
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Referrer-Policy: no-referrer

{"error":"415 UNSUPPORTED_MEDIA_TYPE \"Content type 'application/x-www-form-urlencoded' not supported for bodyType=test.package.Pojo\””}


配置类-

@Bean
public RouterFunction<ServerResponse> testRoute() {
    return route(POST(“/app/test”).and(contentType(MediaType.APPLICATION_FORM_URLENCODED)),
            handler::testHandler);
}


处理程序类

public Mono<ServerResponse> testHandler(final ServerRequest request) {

    return dataManager.testSave(request.bodyToMono(Pojo.class))
            .flatMap(uri -> ServerResponse.ok().build())
            .switchIfEmpty(ServerResponse.badRequest().build());
}


更新了Handler类代码

处理程序类


return dataManager.testSave(request.bodyToMono(String.class)
        .flatMap(body -> Mono.just(URLDecoder.decode(body, StandardCharsets.UTF_8))
                .map(s -> createBody(s))).cast(Pojo.class))
        .flatMap(uri -> ServerResponse.ok().build())
        .switchIfEmpty(ServerResponse.badRequest().build());



private Pojo createBody(String s)  {
    XmlMapper mapper = new XmlMapper();
    Pojo pojo = new Pojo();
    try {
        pojo = mapper.readValue(s, Pojo.class);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return pojo;
}


POJO课

@XmlRootElement(name = “root”)
public class Pojo {

@XmlElement(name = “id”)
public long getId() {
    return id;
}

public void setId(long id) {
    this.id= id;
}

}

最佳答案

我们偏离了处理标准“ Content-type:application / xml”的位置,因此这里添加了3个其他步骤-

1)解码(百分比编码的请求正文)有效负载

2)将解码后的字符串编码为XML

3)将XML转换为Mono

代码更改:

处理函数:

像托马斯建议的那样-

request.bodyToMono(String.class).flatmap(body -> Mono.just(decode(body)).map(decodedstring -> createXML(decodedstring))).cast(Pojo.class))




private String decode(String body){
String str1 = "";
String str2 = body;

//if percent content is re-encoded multiple times
while(!str1.equals(str2)) {
str1=str2;
str2=URLDecoder.decode(str2,StandardCharsets.UTF_8)
}
return str2;
}




private Pojo createXML(String decodedstring) {
InputStream is = new ByteArrayInputStream(decodedstring.getBytes(Charset.forName("UTF-8")));
Pojo pojo = JAXB.unmarshal(is, Pojo.class);
return pojo;
}

关于java - 如何使用Spring Web Flow处理url编码的有效负载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61764553/

10-11 02:36