How to set content type = "application/json" in mule.?

Raman picture Raman · Aug 4, 2011 · Viewed 8.9k times · Source

I have a HTML file which consists of a Form and it takes certain parameters from the User and when the URL is hit, a Mule service (written in Java) is called and it returns a JSON string. Now how can I set Content-type = application/json in either Mule or Java, so that browser know that it is getting a JSON?

My Mule config file is :

<custom-transformer name="HttpParams" class="org.mule.transport.http.transformers.HttpRequestBodyToParamMap" />
<message-properties-transformer name="HttpResponse">
    <add-message-property key="Content-Type" value="application/json" />
    <add-message-property key="http.status" value="303" />
</message-properties-transformer>

<flow name="jcars">
    <http:inbound-endpoint address="http://localhost:11221/jcars" transformer-refs="HttpParams" responseTransformer-refs="HttpResponse">
        <not-filter>
           <wildcard-filter pattern="/favicon.ico"/>
        </not-filter>
    </http:inbound-endpoint>

    <component class="defaults.basicapp.jcars"/>
</flow>

And my Java class is (Jcars) :

public String onEvent(Object obj){

     String json = "{{"id":0,"model":"suzuki","make":"2002","ps":true,"price":101.2,"bhp":12.6},{"id":0,"model":"suzuki","make":"2003","ps":true,"price":101.2,"bhp":12.6},{"id":0,"model":"suzuki","make":"2004","ps":true,"price":101.2,"bhp":12.6},{"id":0,"model":"suzuki","make":"2005","ps":true,"price":101.2,"bhp":12.6},{"id":0,"model":"suzuki","make":"2006","ps":true,"price":101.2,"bhp":12.6}}";

     return json;
}

The browser is displaying the string as it is. It does not know that the content type is application/json. What should I do?

Answer

David Dossot picture David Dossot · Aug 4, 2011

Add a response message properties transformer in your flow in order to set the content type:

<response>
  <message-properties-transformer>
    <add-message-property key="Content-Type" value="application/json" />
  </message-properties-transformer>
</response>