如何在没有内容类型标题的情况下从请求访问请求正文

时间:2018-09-12 17:48:52

标签: java playframework

我认为这对Play来说是一个棘手的问题。很多人提出了这个问题,但是如果在Java中未设置内容类型,仍然不清楚如何从请求正文中获取字节。

Scala中有一个解决方案,但不适用于我的情况。 我想使用Play在Java测试中构建一个http模拟服务器。

@ BodyParser.Of(BodyParser.Raw.class)没有道理

package org.dan;

import org.junit.Test;
import play.mvc.BodyParser;
import play.mvc.Result;
import play.server.Server;

//import static play.mvc.Controller.request;
import static play.mvc.Results.ok;
import static play.routing.RoutingDsl.fromComponents;
import static play.server.Server.forRouter;

import static play.mvc.Http.Context.Implicit.request;

public class DemoPlayTest {
    @Test
    public void run() throws InterruptedException {
        Server server = forRouter(
                9001,
                (components) ->
                        fromComponents(components)                                
                                .POST("/echo")
                                .routeTo(DemoPlayTest::action)
                                .build());
        Thread.sleep(1111111);
    }

    @BodyParser.Of(BodyParser.Raw.class)
    public static Result action() {
        return ok("Gut: " + request().body().asRaw() + "\n");
    }
}

测试:

$ curl -v -X POST -d hello  http://localhost:9001/echo
Gut: null

依赖项:

     <play.version>2.6.17</play.version>
     <dependency>
        <groupId>com.typesafe.play</groupId>
        <artifactId>play-server_2.11</artifactId>
        <version>${play.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.typesafe.play</groupId>
        <artifactId>play-akka-http-server_2.11</artifactId>
        <version>${play.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.typesafe.play</groupId>
        <artifactId>play-java_2.11</artifactId>
        <version>${play.version}</version>
        <scope>test</scope>
    </dependency>

1 个答案:

答案 0 :(得分:0)

package org.dan;

import org.junit.Test;
import play.mvc.Result;
import play.server.Server;

import static play.mvc.Controller.request;
import static play.mvc.Results.ok;
import static play.routing.RoutingDsl.fromComponents;
import static play.server.Server.forRouter;

public class DemoPlayTest {    
    @Test
    public void run() throws InterruptedException {
        Server server = forRouter(
                9001,
                (components) ->
                        fromComponents(components)                                    
                                .POST("/echo")
                                .routeTo(DemoPlayTest::action)
                                .build());
        Thread.sleep(1111111);
    }

    public static Result action() {
        final String body = new String(request().body().asBytes().toArray());
        return ok("Gut: " + body + "\n");
    }
}