Set JSON content-type on s:HttpService in flex

两盒软妹~` 提交于 2020-01-01 09:24:22

问题


I am trying to set the json content type on httpservice to make REST service return the json data. When I add the content type in fiddler all works fine so the problem lays in flex application, not in the web-service. But the code below does not work and I get the xml data instead of json.

Could anyone provide me the workaround/solution?

mxml:

<s:HTTPService id="service" method="POST" url="server.com" 
               result="loaded(event)" fault="fault(event)" 
               useProxy="false" resultFormat="text">

actionscript:

public function loadAllSamples():void {
    service.contentType = "application/json";
    service.send('something');
}

回答1:


Looks like I have sorted it out. The trick is that Accept header should be added on service:

       var header:Object=new Object();

        **header["Accept"] = "application/json";**

        service.contentType = "application/json";
        service.headers = header;
        service.send('{}');

I wish it could be helpful for somebody. Good luck.




回答2:


Thanks, this was very helpful to me. I simplified the header assignment to:

httpService.headers = { Accept:"application/json" };




回答3:


Thought I'd post a cleaner example.

-------- JsonHttpService.as

package services
{
    import mx.rpc.http.HTTPService;
    import mx.rpc.http.SerializationFilter;

    public class JsonHttpService extends HTTPService
    {
        private var jsonFilter:JsonSerializationFilter = new JsonSerializationFilter();

        public function JsonHttpService(rootURL:String=null, destination:String=null)
        {
            super(rootURL, destination);
            resultFormat = "json";
        }

        override public function get serializationFilter():SerializationFilter {
            return jsonFilter;
        }
    }
}

--- JsonSerializationFilter.as

package services
{
    import mx.rpc.http.AbstractOperation;
    import mx.rpc.http.SerializationFilter;

    public class JsonSerializationFilter extends SerializationFilter
    {
        public function JsonSerializationFilter() {
            SerializationFilter.registerFilterForResultFormat("json", this);
            super();
        }

        override public function deserializeResult(operation:AbstractOperation, result:Object):Object {
            return JSON.parse(result as String);
        }

        override public function getRequestContentType(operation:AbstractOperation, obj:Object, contentType:String):String {
            return "application/json";
        }

        override public function serializeBody(operation:AbstractOperation, obj:Object):Object {
            return JSON.stringify(obj);
        }
    }
}


来源:https://stackoverflow.com/questions/4196139/set-json-content-type-on-shttpservice-in-flex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!