Reputation: 1705
I'm getting an error when posting to a simple hello controller in micronaut. The client seems to be posting as application/json but the controller expects text/plain. How do I fix the client to post as text/plain?
HelloController.java
@Post(value = "/helloBody/{name}", consumes = MediaType.TEXT_PLAIN)
public Single<String> helloBody(@NotBlank String name, @NotBlank @Body String text) {
return Single.just(name + "sent: " + text);
}
HelloClient.java
@Post(value = "/helloBody/{name}")
Single<String> helloBody(@NotBlank String name, @NotBlank String body);
HelloControllerTest.java
@Test
void testPost() {
String body = client.helloBody("John", "message").blockingGet();
assertThat(body).isEqualTo("John sent: message");
}
Error
io.micronaut.http.client.exceptions.HttpClientResponseException: Content Type [application/json] not allowed. Allowed types: [text/plain]
at io.micronaut.http.client.DefaultHttpClient$10.channelRead0(DefaultHttpClient.java:1799)
at io.micronaut.http.client.DefaultHttpClient$10.channelRead0(DefaultHttpClient.java:1739)
at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360)
...
Upvotes: 2
Views: 6298
Reputation: 9082
You can change this by tell the client to send text/plain
as the backend expects.
@Post(value = "/helloBody/{name}", consumes = MediaType.TEXT_PLAIN, produces = MediaType.TEXT_PLAIN)
Single<String> helloBody(@NotBlank String name, @NotBlank String body);
The idea in Micronaut is to make web operations shareable between a controller and a client.
Let's think of a interface called HelloOperations
. This is your web interface that can be shared between the client and server.
@Validated
public interface HelloOperations {
@Post(value = "/helloBody/{name}", consumes = MediaType.TEXT_PLAIN)
Single<String> helloBody(@NotBlank String name, @NotBlank @Body String text);
}
Now you start implementing the contract in the backend with a controller implementation such as
@Controller
public class HelloController implements HelloOperations {
@Override
public Single<String> helloBody(String name, String text) {
// do something in here...
}
}
after that you continue on the client side.
@Client
public interface HelloWorldClient extends HelloOperations {
@Override
Single<String> helloBody(String name, String text);
}
Et voilà. You successfully connected them.
Further explanations can be found in the Micronaut documentation at https://docs.micronaut.io/latest/guide/index.html#clientAnnotation
Upvotes: 4