简体   繁体   中英

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

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM