DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How To Check for JSON Insecure Deserialization (JID) Attacks With Java
  • MuleSoft Integration With RabbitMQ
  • How to Connect to Splunk Through Anypoint Studio in 10 Steps
  • Page Object Model for Performance Testing With Gatling

Trending

  • Why Database Migrations Take Months and How to Speed Them Up
  • The Future of Java and AI: Coding in 2025
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  • Agentic AI for Automated Application Security and Vulnerability Management
  1. DZone
  2. Coding
  3. Languages
  4. Micronaut Mastery: Return Responses Based on the HTTP Accept Header

Micronaut Mastery: Return Responses Based on the HTTP Accept Header

Take a look at how to get your Micronaut-based microservice to format its response based on a request's Accept header.

By 
Hubert Klein Ikkink user avatar
Hubert Klein Ikkink
·
Aug. 24, 18 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
20.4K Views

Join the DZone community and get the full member experience.

Join For Free

Suppose we want our controller methods to return a JSON response when the HTTP Accept header is set to application/json and XML when the Accept header is set to application/xml. We can access the values of HTTP headers in our controller methods by adding an argument of type HttpHeaders to our method definition and Micronaut will add all HTTP headers with their values as HttpHeaders object when we run the application. In our method, we can check the value of the Accept header and return a different value based on the header value.

In the following example controller, we have a sample method with an argument of the type HttpHeaders. We check the value of the Accept header using the method accept and return either XML or JSON as the response.

package mrhaki.micronaut;

import io.micronaut.http.HttpHeaders;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;

@Controller("/message")
public class MessageController {

    @Get("/")
    public HttpResponse<?> sample(final HttpHeaders headers) {
        // Simple object to be returned from this method either
        // as XML or JSON, based on the HTTP Accept header.
        final Message message = new Message("Micronaut is awesome");

        // Check if HTTP Accept header is "application/xml".
        if (headerAcceptXml(headers)) {
            // Encode messages as XML.
            final String xml = encodeAsXml(message);

            // Return response and set content type 
            // to "application/xml".
            return HttpResponse.ok(xml)
                               .contentType(MediaType.APPLICATION_XML_TYPE);
        }

        // Default response as JSON.
        return HttpResponse.ok(message);
    }

    /**
     * Check HTTP Accept header with value "application/xml"
     * is sent by the client.
     * 
     * @param headers Http headers sent by the client.
     * @return True if the Accept header contains "application/xml".
     */
    private boolean headerAcceptXml(final HttpHeaders headers) {
        return headers.accept().contains(MediaType.APPLICATION_XML_TYPE);
    }

    /**
     * Very simple way to create XML String with message content.
     * 
     * @param message Message to be encoded as XML String.
     * @return XML String with message content.
     */
    private String encodeAsXml(final Message message) {
        return String.format("<content>%s</content>", message.getContent());
    }

}

The Message class that is converted to XML or JSON is simple:

package mrhaki.micronaut;

public class Message {

    final String content;

    public Message(final String content) {
        this.content = content;
    }

    public String getContent() {
        return content;
    }

}

When we run the application and GET /message with the HTTP Accept header value application/xml, we get the following response:

<content>Micronaut is awesome</content>

And with the HTTP Accept header value application/json, we get the following response:

{
    "content": "Micronaut is awesome"
}

We can test our controller with the following Spock specification:

package mrhaki.micronaut

import io.micronaut.context.ApplicationContext
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus
import io.micronaut.http.MediaType
import io.micronaut.http.client.RxHttpClient
import io.micronaut.runtime.server.EmbeddedServer
import spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification

class MessageControllerSpec extends Specification {

    @Shared
    @AutoCleanup
    private static EmbeddedServer embeddedServer =
            ApplicationContext.run(EmbeddedServer)

    @Shared
    @AutoCleanup
    private static RxHttpClient client =
            embeddedServer.applicationContext
                          .createBean(RxHttpClient, embeddedServer.getURL())

    void "get message as XML"() {
        given:
        final request = HttpRequest.GET("/message").accept(MediaType.APPLICATION_XML_TYPE)
        HttpResponse response = client.toBlocking().exchange(request, String)

        expect:
        response.status == HttpStatus.OK
        response.body() == 'Micronaut is awesome' } void "get message as JSON"() { given: HttpResponse response = client.toBlocking().exchange("/message", Message) expect: response.status == HttpStatus.OK response.body().getContent() == 'Micronaut is awesome' } }

Written with Micronaut 1.0.0.M4.

application XML JSON Spock (testing framework) Testing Object (computer science)

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Check for JSON Insecure Deserialization (JID) Attacks With Java
  • MuleSoft Integration With RabbitMQ
  • How to Connect to Splunk Through Anypoint Studio in 10 Steps
  • Page Object Model for Performance Testing With Gatling

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!