【问题标题】:QBit POST method not able to parse plaintextQBit POST 方法无法解析明文
【发布时间】:2016-03-24 16:46:05
【问题描述】:

我正在使用 Qbit 编写一个简单的 REST 应用程序,但无法正确解析 POST 编辑的文本。这几乎是straight out of a tutorial,所以我不确定我可能会错过什么

在 SimpleService.java 中

@RequestMapping(value = "/body/string", method = RequestMethod.POST)
public boolean bodyPostString(String body) {
    return body.equals("foo");
}

...

public static void main(final String... args) {

        final ServiceEndpointServer serviceServer = EndpointServerBuilder
            .endpointServerBuilder()
            .setUri("/")
            .build();
    serviceServer.initServices(
            new SimpleService());
    serviceServer.startServer();

在终端中

 curl -X POST -H "Content-Type: text/plain" -d 'foo' http://localhost:8080/service/body/string

回复

["Unable to JSON parse body :: false not parsed properly\n\nThe current character read is 'f' with an int value of 102\nfalse not parsed properly\nline number 1\nindex number 0\nfoo\n^"]

【问题讨论】:

    标签: java rest curl


    【解决方案1】:

    这可能是我使用的 QBit 版本 (0.9.3) 的问题,但是我能够通过将我的 POST 正文包装在 JSON 中并使用 advantageous boon 解析它来解决这个问题(我假设) 因为所有 JSON 都由 QBit 处理。

    在一个新类中,SimpleJSONWrapper:

    import java.util.Map;
    
    public class SimpleJSONWrapper {
    
        public final String payload;
    
        public SimpleJSONWrapper(final String payload) {
            this.payload = payload;
         }
    
        public String getPayload() {
            return payload;
        }
    }
    

    原来的bodyPostString方法变成了:

    @RequestMapping(value = "/body/string", method = RequestMethod.POST)
    public boolean bodyPostString(SimpleJSONWrapper body) {
        return body.getPayload().equals("foo");
    }
    

    现在将您的请求发送为:

    curl -X POST -H "Content-Type: text/plain" -d '{\"payload\":\"foo\"}' http://localhost:8080/service/body/string
    

    注意,如果您有嵌套的 JSON 作为您的有效负载,您将需要您的 SimpleJSONWrapper 来存储 Map<String, Object>,而不是 String

    【讨论】:

      猜你喜欢
      • 2015-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-15
      • 2015-06-10
      相关资源
      最近更新 更多