在flex中设置s:HttpService的JSON内容类型

lsmd5eda  于 2022-11-01  发布在  Apache
关注(0)|答案(3)|浏览(141)

我尝试在httpservice上设置json内容类型,以使REST服务返回json数据。当我在fiddler中添加内容类型时,所有工作都正常,所以问题出在flex应用程序上,而不是Web服务上。但下面的代码不起作用,我得到的是xml数据而不是json。
有人能为我提供变通方法/解决方案吗?
mxml文件:

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

动作脚本:

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

zqdjd7g91#

看起来我已经整理好了。诀窍是在服务上添加Accept头:

var header:Object=new Object();

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

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

我希望它能对某人有帮助祝你好运。

8ehkhllq

8ehkhllq2#

谢谢,这对我很有帮助。我将标题分配简化为:
httpService.headers = { Accept:"application/json" };

k10s72fa

k10s72fa3#

我想我应该发布一个更清晰的例子。
--------------------------------------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);
        }
    }
}

相关问题