阿卡HTTP分析实体的Java

问题描述 投票:1回答:1

我有一个处理传入的HTTP请求的代码如下

public Function < HttpRequest, HttpResponse > handleRequest() {
  return new Function < HttpRequest, HttpResponse > () {

    private static final long serialVersionUID = 1 L;

    @Override
    public HttpResponse apply(HttpRequest request) throws Exception {
      System.out.print(request);

      return HttpResponse.create()
        .withEntity(ContentTypes.TEXT_PLAIN_UTF8, "Success")
        .withStatus(StatusCodes.OK);
    }
  }
}

在控制台我得到这样的结果。

HttpRequest(HttpMethod(POST),http://localhost:8081/,List(Host: localhost:8081, Connection: keep-alive, Authorization: Basic YTph, Postman-Token: 1e3189b0-f320-5926-a781-a9c05e5cbd6a, Cache-Control: no-cache, Origin: chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop, User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36, Accept: */*, Accept-Encoding: gzip, deflate, br, Accept-Language: en-US, en;q=0.9, Timeout-Access: <function1>),HttpEntity.Strict(application/json,{
	"name" : "John Doe"
}),HttpProtocol(HTTP/1.1))

所以,我想获得JSON来像这样的字符串变量

{"name" : "John Doe"}
java http akka akka-http
1个回答
1
投票

你需要让HttpEntityStrict并从它消耗所有的身体。

import akka.actor.ActorSystem;
import akka.http.javadsl.ConnectHttp;
import akka.http.javadsl.Http;
import akka.http.javadsl.IncomingConnection;
import akka.http.javadsl.ServerBinding;
import akka.http.javadsl.model.*;
import akka.japi.function.Function;
import akka.stream.ActorMaterializer;
import akka.stream.javadsl.Sink;
import akka.stream.javadsl.Source;
import akka.util.ByteString;
import scala.concurrent.duration.FiniteDuration;

import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;

public class JavaHttpRequest {

    public static void main(String[] args) {
        final ActorSystem system = ActorSystem.create();
        final ActorMaterializer materializer = ActorMaterializer.create(system);

        Source<IncomingConnection, CompletionStage<ServerBinding>> serverSource =
                Http.get(system).bind(ConnectHttp.toHost("localhost", 8080));


        serverSource.to(Sink.foreach(connection -> {
            System.out.println("Accepted new connection from " + connection.remoteAddress());

            connection.handleWithSyncHandler(handleRequest(materializer), materializer);
        })).run(materializer);
    }

    private static Function<HttpRequest, HttpResponse> handleRequest(ActorMaterializer materializer) {
        return request -> {
            try {
                System.out.print(getString(materializer, request));
            } catch (Exception e) {
                e.printStackTrace();
            }

            return HttpResponse.create()
                    .withEntity(ContentTypes.TEXT_PLAIN_UTF8, "Success")
                    .withStatus(StatusCodes.OK);
        };
    }

    private static String getString(ActorMaterializer materializer, HttpRequest request) throws Exception {
        final CompletionStage<HttpEntity.Strict> strictEntity = request.entity()
                .toStrict(FiniteDuration.create(3, TimeUnit.SECONDS).toMillis(), materializer);

        final CompletionStage<String> stringStage = strictEntity
                .thenCompose(strict ->
                        strict.getDataBytes()
                                .runFold(ByteString.empty(), ByteString::concat, materializer)
                                .thenApply(ByteString::utf8String)
                );

        return stringStage.toCompletableFuture().get();
    }

}

在发送HTTP请求

curl -X POST \
  http://localhost:8080/hello/json \
  -H 'Content-Type: application/json' \
  -d '{"test": "hello"}'

打印{"test": "hello"}

© www.soinside.com 2019 - 2024. All rights reserved.