append a request body to vertx request - java

IN my java sample code of a vertex URL instance below, The URL returns a json request when called. I am trying to append a request body to the URL but I am stuck. Here is a sample snippet
Route handler2 = router
.post("/get-a-file")
.consumes("*/json")
.handler(routingContext -> {
HttpServerResponse response = routingContext.response();
response.setChunked(true);
response.write("bla bla bla...");
response.end();
});
Just getting my hands on vert.x. Do assist

For request bodies in Vert.x your route needs a BodyHandler. You should add it before your own handler so that the request body is already there when your business logic runs.
Your code should look similar to this:
...
.consumes("*/json")
.handler(BodyHandler.create())
.handler(routingContext -> ...
Now you can access the body on routingContext and map it to your DTO.

Related

how to insert body in a post request with akka library using java

have to use akka library with java and i need to do a post request with body in it, a body like this: {"subjectId":961,"other":null}
In this application, I have some examples already written with get requests and parameters to those requestes. but now i need to send a post request with body in it.
The following snippet is correct? if not, can you tell me what i do wrong? thanks.
..
Http http = new Http((ExtendedActorSystem) context().system());
HttpRequest postRequest = HttpRequest.POST(url)
.withEntity(MediaTypes.APPLICATION_JSON.toContentType(),
"{\"subjectId\": 961, \"other\": null,}");
CompletionStage<HttpResponse> response = http.singleRequest(postRequest);
..

SparkJava GET Handler Returning NULL After Serialization of Long

I'm trying to write a simple server with SparkJava but I am having considerable difficulty serialize a long using Gson and transmitting the JSON to an OkHttp client program inside a GET handler. The server returns NULL, more specifically response.body.string() is
<html><body><h2>404 Not found</h2></body></html>
Any ideas on what the issue could be? thanks.
Here is the GET handler:
get("routingEngine/getDefaultRoute/distance", (request,response) ->{
response.type("application/json");
long distance = 100;
return gson.toJson(distance);
});
Here is the client code making the simple request (please disregard the parameters (requestParameters) being passed in along with the request, they just provide information to an irrelevant before filter):
// build url
HttpUrl url = new HttpUrl.Builder()
.scheme("http")
.host("127.0.0.1")
.port(4567)
.addPathSegment("routingEngine")
.addPathSegment("getDefaultRoute")
.addPathSegment("distance")
.build();
// build request
Request getDefaultRouteDistanceRequest = new Request.Builder()
.url(url)
.post(RequestBody.create(JSON,gson.toJson(requestParameters)))
.build();
// send request
Call getDefaultRouteDistanceCall = httpClient.newCall(getDefaultRouteDistanceRequest);
Response getDefaultRouteDistanceResponse = getDefaultRouteDistanceCall.execute();
// parse response
// testing
System.out.println(getDefaultRouteDistanceResponse.body().string());
The last line leads to the following output
<html><body><h2>404 Not found</h2></body></html>
The endpoint you created was a GET endpoint and the call being made is for POST.

Spring webclient how to extract response body multiple times

how to re-use webclient client response? I am using webclient for synchronous request and response. I am new to webclient and not sure how to extract response body in multiple places
WebClient webClient = WebClient.builder().baseUrl("http://localhost:8080").build();
below is my call to API which returns valid response
ClientResponse clientResponse;
clientResponse = webClient.get()
.uri("/api/v1/data")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.block();
How to use clientResponse in multiple places? only one time I am able to extract response body
String response = clientResponse.bodyToMono(String.class).block(); // response has value
When I try to extract the response body second time (in a different class), it's null
String response = clientResponse.bodyToMono(String.class).block(); // response is null
So, can someone explain why response is null second time and how to extract the response body multiple times?
WebClient is based on Reactor-netty and the buffer received is one time thing.
One thing you could do is to cache the result at the first time and then reuse it.
You can refer to this issue in spring cloud gateway: https://github.com/spring-cloud/spring-cloud-gateway/issues/1861
Or refer to what Spring Cloud gateway do for caching request body: https://github.com/spring-cloud/spring-cloud-gateway/blob/master/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/AdaptCachedBodyGlobalFilter.java
Or you can write your code like:
String block = clientResponse.bodyToMono(String.class).block();
And next time you can use this body:
Mono.just(block);

How to send HTTP-Request from my IntegrationFlow?

I receive a Request from the Client which returns a SendRequest-Object that has a HttpMethod, a path and data to send.
Now I would like to send the Request depending on the object I get to the API.
After sending I will get a Response.
The problem now is how can I send the payload and receive the response.
#Bean
public IntegrationFlow httpPostSendRawData() {
return IntegrationFlows.from(
Http.inboundGateway("/api/data/send")
.requestMapping(r -> r.methods(HttpMethod.POST))
.statusCodeExpression(dataParser().parseExpression("T(org.springframework.http.HttpStatus).BAD_REQUEST"))
.requestPayloadType(ResolvableType.forClass(DataSend.class))
.crossOrigin(cors -> cors.origin("*"))
.headerMapper(dataHeaderMapper())
)
.channel("http.data.send.channel")
.handle("rawDataEndpoint", "send")
.transform(/* here i have some transformations*/)
.handle(Http.outboundGateway((Message<SendRequest> r)->r.getPayload().getPath())
.httpMethod(/* Here I would like to get the Method of SendRequest*/)
//add payload
.extractPayload(true))
.get();
It's not clear what is your SendRequest, but the idea for the method is exactly the same what you have done for the url:
.httpMethodFunction((Message<SendRequest> r)->r.getPayload().getMethod())
Although, since you want to have some extraction for the request body, you need to do that in advance in the transform() and move values for url and method to the headers.
There is just no any payload extraction in the Http.outboundGateway: it deals with the whole request payload as an entity for HTTP request body.

How to separate the execution of an HTTP request from the parsing of the HTTP response body using Spring WebClient?

I want to separate the execution of an HTTP request from the parsing of the HTTP response body using Spring WebClient.
I want to write tests that test each of these concerns separately so that I can easily identify where an issue exists (in the execution of the request or in the parsing of the response body). I don't want the request call to fail because the response was a primitive string even though I was expecting JSON.
WebClient only seems to be able to execute a request and parse the response's body in one step:
var responseBody = client.get().uri(endpoint).retrieve().bodyToMono(String.class).block();
I want to do something like this:
var response = client.get().uri(endpoint).retrieve().block();
var responseBody = response.bodyToMono(String.class).block();

Categories