操作脚本3 - 将JSON发布到RESTful服务器

时间:2014-11-20 16:25:15

标签: ajax json actionscript-3 flash flex

我尝试使用以下代码将简单的JSON对象发布到RESTfull服务器:

var messages:Array = new Array ();  
messages.push ({"name":"MyName"});

var vars: URLVariables = new URLVariables();
vars.data   = JSON.stringify(messages);

var urlRequest:URLRequest= new URLRequest("http://localhost:8080/xxx/player/createAccount");
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = vars;
var hdr:URLRequestHeader = new URLRequestHeader("Content-type", "application/json");
urlRequest.requestHeaders.push(hdr);

_urlLoader = new URLLoader();
_urlLoader.addEventListener(Event.COMPLETE, onXMLDataLoaded);
_urlLoader.load(urlRequest);

我的对象很简单,它包含一个名为{" name" :" MyName"}

服务器无法识别请求的数据。

网络监视器上的请求显示:

POST http://localhost:8080/xxx/player/createAccount HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 42
Pragma: no-cache
Cache-Control: no-cache
Origin: http://localhost:8080
X-Requested-With: ShockwaveFlash/15.0.0.223
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)     Chrome/39.0.2171.65 Safari/537.36
Content-Type: application/json
Accept: */*
Referer: http://localhost:8080/xxx/flashClient/lobby.swf
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,he;q=0.6
Cookie: JSESSIONID=1841C3CBE7511794A4EEF8A1A0BD56DD

data=%5B%7B%22name%22%3A%22MyName%22%7D%5D

网络监控工具上的工作发布请求如下所示:

POST http://localhost:8080/xxx/player/createAccount HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 20
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)    Chrome/39.0.2171.65 Safari/537.36
Origin: chrome-extension://cdjfedloinmbppobahmonnjigpmlajcd
Content-Type: application/json
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,he;q=0.6
Cookie: JSESSIONID=1841C3CBE7511794A4EEF8A1A0BD56DD

{ "name" : "MyName"}

任何想法如何让第一个请求像第二个请求一样执行?

1 个答案:

答案 0 :(得分:1)

如果您的内容类型为application/json,那么您不希望将[{1}}用于您的数据:

URLVariables

相反,将字符串化的JSON直接分配给//this is causing the problem because it's encoding your JSON string so it's url safe. var vars: URLVariables = new URLVariables(); vars.data = JSON.stringify(messages); 的{​​{1}}属性,如下例所示:

URLRequest

P.S。有一个很好的tutorial可以帮助理解REST范例。