For some reason, I cannot quite pin-point the reason for my application to fail to send a file with the request body. I have tried all manners of configuring the request header, but to no avail. I know it's not my end-point in Laravel because Postman works just fine with it.
Various header comibinations I have tried:
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Transfer-Encoding': 'multipart/form-data'
OR
'Content-Type': 'multipart/form-data',
'Content-Transfer-Encoding': 'multipart/form-data'
OR
'Content-Type': 'application/json; charset=UTF-8',
'Content-Transfer-Encoding': 'multipart/form-data'
When ever I have my endpoint check to see if $request->file('document') is null, it always comes back true.
Here is my api code:
public function store(Request $request)
{
$value = $request->file('document')->storeAs(
$request->input('path'), $request->input('name')
);
return response()->json($value, 201);
}
Here is the last set of header's that was used and failed:
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 164
Content-Transfer-Encoding: multipart/form-data
Content-Type: multipart/form-data; charset=UTF-8
Cookie: remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d=eyJpdiI6IjhZMXRwM3BSYnlsMUdlUHQ1OEVzZkE9PSIsInZhbHVlIjoibFJBV3AxaHU0T3BJY1M5UGRQZG5YdmhxTndWYXRRRHFsZlhEZ0tNa1NqWnlFZndwUGdkeGxFNzZXVW53OUxKMWJ0Q0s3VkFxZTM5T1dKUTdQVE5HbHVhcHBoS29rMllQb1wvbUhKeWFMcjdOOGU3elRYWWlyV3daY1duUUZCb1k1amE3aEVHWEN5SkJLZFVCNnNlRlJIa0hVT2FGb1poVjhCZzVOR21EMUttND0iLCJtYWMiOiI2YjFjYTA5MzcyYzcxMDk4OWFmNzJlNTMzMzQ0ODRkYTZmYzEzZDNjYmQ2YTdiNmZhZWFhODc2NWM0MWExMzZiIn0%3D; XSRF-TOKEN=eyJpdiI6Ikh4R1JhSXJ4M1IycmJTNmFsRjRic0E9PSIsInZhbHVlIjoib0xpQzZqaHRRRFQ3V0RQU0lVT3VSdmU4RFwvS3MwSWpSeTdmOURVZE9kRlhPaTBFeWlBOHljQ1F4aGt0VEFIbWwiLCJtYWMiOiI3MjcyMGM5YzIwZjE5NTFkOTQyNjA3MDlmOTJjMjY0OTg2NGViZWY5NzYwZmJlNGEyYmM0MzFmNDYxMDRlN2U5In0%3D; conversion_session=eyJpdiI6InIwc2NRMzZhc1RZdWZtMDl0OFVMaHc9PSIsInZhbHVlIjoiNmY5MjJUYTNteW5zVG9MVmlmXC90a0FCaTlEY3VhS0w2UXYreUtmdG5yUE5IUnpWVE1qTWthemdnSzRKbmE5NWEiLCJtYWMiOiJjNDkzZTVlNzE0YjBhMDRiNDU3ZmQxMzNlZDkzMjQ1MWQ2YTcxMzYxODU0ZGMyYTFkOTZhYjA2ZmUwNDZhOGQ2In0%3D
Host: conversion:8000
Origin: http://conversion:8000
Referer: http://conversion:8000/accounts/1/projects/1?_token=
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36
X-XSRF-TOKEN: // Not pasted here
I discovered, that I was assigning my post data incorrectly for the files. A tutorial had instructed my incorrectly and I found another one that showed me the correct way.
Related
I want to scrape german poll data from a server. Here, I search for an examplary street, straße "Judengasse".
I have been trying to reproduce this. Unfortunately, the link from the reference is not intact anymore, so I couldn't directly compare it to my problem. Since I am fairly inexperienced, I do not know what is exactly needed to reproduce the request that is submitted via the web interface.
I don't now which attributes of the header are needed for my request to work and what of it might be redundant. In Chrome's inspect mode I see that in my case there are more header attributes than in the referenced example.
My code so far (which does not work) from trying to reproduce the SE post:
import requests
url = 'https://online-service2.nuernberg.de/Finder/action/getItems'
data = {
"finder":"Wahlraumfinder",
"strasse":"Judengasse",
"hausnummer":"0"
}
headers = {
'Host': 'online-service2.nuernberg.de',
'Referer': 'https://online-service2.nuernberg.de/Finder/?Wahlraumfinder',
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7',
'Connection': 'keep-alive',
'Content-Length': '312',
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryeJZfrnZATOw6B5By',
'DNT': '1',
'Host': 'online-service2.nuernberg.de',
'Referer': 'https://online-service2.nuernberg.de/Finder/?Wahlraumfinder',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-origin',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest'
}
response = requests.get(url, data=data, headers=headers)
I don't get a respone. I added all request headers to headers.
Not sure, if more headers are needed.
Further, I am not sure if the url is correct.
I am looking to generate output of the following form, for this specific request "Judengasse":
Nr 0652
Wahllokal Willstätt.-Gym., Innerer Laufer Platz 11
This corresponds to putting in "Judengasse" into the search bar and hitting go on
the search "Suche" and extracting parts of the first output box "Wahl-/Stimmbezirk"
When I look at the XHR in Chrome's dev mode:
General
Request URL: https://online-service2.nuernberg.de/Finder/action/getItems
Request Method: POST
Status Code: 200 OK
Remote Address: 193.22.166.102:443
Referrer Policy: no-referrer-when-downgrade
Response Header
Connection: Keep-Alive
Content-Length: 1149
Content-Type: application/json;charset=UTF-8
Date: Wed, 04 Dec 2019 00:21:30 GMT
Keep-Alive: timeout=5, max=100
Server: Apache
Request Header
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
Connection: keep-alive
Content-Length: 312
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryx2jHYJHo3ejnKw0l
DNT: 1
Host: online-service2.nuernberg.de
Origin: https://online-service2.nuernberg.de
Referer: https://online-service2.nuernberg.de/Finder/?Wahlraumfinder
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36
X-Requested-With: XMLHttpRequest
From Data
------WebKitFormBoundaryx2jHYJHo3ejnKw0l
Content-Disposition: form-data; name="action"
"action/getItems"
------WebKitFormBoundaryx2jHYJHo3ejnKw0l
Content-Disposition: form-data; name="data"
{"finder":"Wahlraumfinder","strasse":"Judengasse","hausnummer":"0"}
------WebKitFormBoundaryx2jHYJHo3ejnKw0l--
Thank you for reading.
After some research I finally managed to get a 200 response from this server.
Firstly, requests.get in this case should be replace by requests.post, since you want to replicate an HTTP POST request, according to the info you got from Chrome's dev mode, "General" section.
Secondly, from the headers we can see that the data is sent as being of type "multipart/form-data" request. As far as I could understand, this is a type of request that is used to send files instead of regular data (more about this type of request here).
So, I converted the string sent through the POST request to binary (this is achieved by prepending b) and passed it to the files parameter of the request. For some reason, this parameter requires a tuple (a, b) inside a set {c}, hence the {(None, data)}.
I also passed the street name as a parameter to data, so it's easier to manipulate it.
I got this working code (I'm using my browser's request):
import requests
url = 'https://online-service2.nuernberg.de/Finder/action/getItems'
street = b'Judengasse'
data = b'-----------------------------15242581323522\r\n' \
b'Content-Disposition: form-data; name=\"action\"\r\n\r\n' \
b'\"action/getItems\"\r\n-----------------------------15242581323522\r\n' \
b'Content-Disposition: form-data; name="data"\r\n\r\n' \
b'{\"finder\":\"Wahlraumfinder\",\"strasse\":\"%s\",\"hausnummer\":\"0\"}\r\n' \
b'-----------------------------15242581323522--' % street
headers = {"Host": "online-service2.nuernberg.de",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0",
"Accept": "*/*",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate, br",
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "multipart/form-data; boundary=---------------------------15242581323522",
"Content-Length": "321",
"Origin": "https://online-service2.nuernberg.de",
"DNT": "1",
"Connection": "keep-alive",
"Referer": "https://online-service2.nuernberg.de/Finder/?Wahlraumfinder",
}
multipart_data = {(None, data,)}
response = requests.post(url, files=multipart_data, headers=headers)
print(response.text)
I got this raw response:
{"id":"8c4f7a57-1bd6-423a-8ab8-e1e40e1e3852","items":[{"zeilenbeschriftung":"Wahl-/Stimmbezirk","linkAdr":null,"mapUrl":"http://online-service.nuernberg.de/Themenstadtplan/sta_gebietsgli
ederungen.aspx?p_urlvislayer=Stimmbezirke&XKoord=4433503.05&YKoord=5480253.301&Zaehler=1&Textzusatz=Judengasse+0&z_XKoord=4433670.0&z_YKoord=5480347.0&z_Zaehler=1&z_Textzusatz=Wahllokal%
20Willst%E4tt.-Gym.%2C+Innerer+Laufer+Platz+11","items":["0652","Judengasse, Neue Gasse","Willstätt.-Gym., Innerer Laufer Platz 11","Zi. 101 ,1. OG",null]},{"zeilenbeschriftung":"Stimmkr
eis Landtagswahl","linkAdr":null,"mapUrl":"http://online-service.nuernberg.de/Themenstadtplan/sta_gebietsgliederungen.aspx?p_urlvislayer=Stimmkreis_LTW&XKoord=4433503.05&YKoord=5480253.3
01&Zaehler=1&Textzusatz=Judengasse+0&p_scale=100000","items":["501","Nürnberg-Nord"]},{"zeilenbeschriftung":"Wahlkreis Bundestagswahl","linkAdr":null,"mapUrl":"http://online-service.nuer
nberg.de/Themenstadtplan/sta_gebietsgliederungen.aspx?p_urlvislayer=Wahlkreis_BTW&XKoord=4433503.05&YKoord=5480253.301&Zaehler=1&Textzusatz=Judengasse+0&p_scale=150000","items":["244","N
ürnberg-Nord"]}],"status":200}
which you can easily parse to get the result you expect:
print(response.json()["items"][0]["items"])
yilding...
['0652', 'Judengasse, Neue Gasse', 'Willstätt.-Gym., Innerer Laufer Platz 11', 'Zi. 101 ,1. OG', None]
Hope it helps.
Regards
Intro
There is a #GetMapping attribute, as the following in one of our projects:
#GetMapping(path = "/", produces = SaConstants.SA_MEDIA_TYPE)
public HttpEntity<Resource<Home>> get(HttpServletResponse response) {
In the SaConstants class:
public static final String SA_MEDIA_TYPE="application/sa+json";
When I access the page from any internet browser, I am getting the proper response that I want - and my breakpoint in the controller is being triggered.
The browser is sending the following headers:
Host: 127.0.0.1:8001
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
DNT: 1
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Cookie: io=Qt74kp5V5ziUNIxlAAAG
When I make a request to the page, without an Accept header, the page is not working.
If I add to postman the following Accept header, everything works:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Question
My question are:
why does it work even if the Accept: header of the request doesn't match the produces attribute of the Rest Controller?
Why does it fail if no Accept header is provided (given the first question).
"*/*" means all types, this header is by default provided by most of the popular browsers
Asp MVC 5 app deployed on IIS 8.5.
Need to enable ajax request from a number of clients.
Server-side I have In WebApiConfig.cs
config.EnableCors();
In controller:
[EnableCors(origins: "http://localhost:59901", headers: "*", methods: "*", SupportsCredentials = true)]
public class ItemController : Controller
Client side
$("#getItem").on("click", function (e) {
var myurl = "http://servername/item/details/1"
$.ajax({
url: myurl,
type: "GET",
dataType: "JSON",
xhrFields: {
withCredentials: true
},
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
$('#result').text(jqXHR.responseText || textStatus);
},
success: function (result) {
$('#result').text(result);
}
});
});
Running client from VisualStudio Origin is http://localhost:59901.
Running the ajax request I get the following in fiddler:
1. Preflight request/response
OPTIONS http://vrtsrv01.webdev.local/item/details/1 HTTP/1.1
Host: vrtsrv01.webdev.local
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:59901
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost:59901/Home/Index
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,it;q=0.6,it-IT;q=0.4
HTTP/1.1 200 OK
Server: Microsoft-IIS/8.5
Access-Control-Allow-Origin: http://localhost:59901
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, MaxDataServiceVersion
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Credentials: true
X-Powered-By: ASP.NET
Date: Sat, 13 May 2017 15:34:54 GMT
Content-Length: 0
2. GET request without credentials/ 401 error response
GET http://vrtsrv01.webdev.local/item/details/1 HTTP/1.1
Host: vrtsrv01.webdev.local
Connection: keep-alive
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:59901
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Content-Type: application/json; charset=utf-8
Referer: http://localhost:59901/Home/Index
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,it;q=0.6,it-IT;q=0.4
HTTP/1.1 401 Unauthorized
Cache-Control: private
Content-Type: text/html
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
X-Powered-By: ASP.NET
Date: Sat, 13 May 2017 15:34:54 GMT
Content-Length: 1352
Proxy-Support: Session-Based-Authentication
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>401 - Autorizzazione negata: accesso negato a causa di credenziali non valide.</title>
....
</head>
<body>
<div id="header"><h1>Errore del server</h1></div>
....
</body>
</html>
3. GET request with NTLM token for auth / response without Allow CORS header
GET http://vrtsrv01.webdev.local/item/details/1 HTTP/1.1
Host: vrtsrv01.webdev.local
Connection: keep-alive
Authorization: Negotiate <...NTLM TOKEN HERE ...>
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:59901
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Content-Type: application/json; charset=utf-8
Referer: http://localhost:59901/Home/Index
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,it;q=0.6,it-IT;q=0.4
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.5
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
Persistent-Auth: true
X-Powered-By: ASP.NET
Date: Sat, 13 May 2017 15:34:58 GMT
Content-Length: 8557
{"id":1, .....}
QUESTION
Why after enabling MVC app for CORS and seeing the right response to preflight request, the response obtained after NTLM authentication does not contain the expected Access-Control-Allow-Origin header?
I'm not sure that it will help you, but it might help someone else looking to have both NTLM and CORS enabled.
CORS enabling
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var corsAttr = new EnableCorsAttribute("*", "*", "*") { SupportsCredentials = true };
//SupportsCredentials = true means that we will add Access-Control-Allow-Credentials to the response.
config.EnableCors(corsAttr);
}
}
SupportsCredentials = true means that we will add Access-Control-Allow-Credentials to the response.
Other solutions,
global.asax.cs - properly reply with headers that allow caller from another domain to receive data
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (Context.Request.HttpMethod == "OPTIONS")
{
Context.Response.AddHeader("Access-Control-Allow-Origin", Context.Request.Headers["Origin"]);
Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,MaxDataServiceVersion");
Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
Context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
Context.Response.End();
}
}
SOLVED (...for now...)
The invoked action was a controller action returning Json. This does not work with CORS. I need to create an API controller, cannot use the existing controller. This leads to code duplication, but I have no time now to refactor the whole application to use a single controller both for MVC and API
I want to sent a Symfony form through AJAX (AngularJS).
However, even if data is clearly sent, the form is said by Symfony to be "not submitted" (no error actually, but some debug show that isSubmitted returns false)
Here is a test on FOSUserBundle registration form.
EDIT: although pictures appear small, they are sufficiently resolved so that they are perfectly readable if displayed at their full size.
Here are the logs when I use a standard submission from an HTTP form:
Here are the logs when I use AJAX submission:
I have disabled CSRF token
The method I use from AJAX is "post" so it should be ok since it is the default Symfony expects (and FOSUserBundle does not override that default AFAIK).
Other forms (outside of FOSUserBundle scope) are correctly sent with AJAX
Would you have any idea on the matter? Any pointer? Or any other log I could check?
EDIT:
I use the default FOSUserBundle registration controller.
I almost use the default FOSUserBundle registration form, but I have added a (currently) empty child form which I'll need it further in the development.
namespace NONG\SecurityBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class UserRegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options) {}
public function getParent() {
return 'fos_user_registration';
}
public function getName() {
return 'nong_user_registration';
}
}
Headers and data sent with the HTML form (NB. added a dot before star in Accept so that the coloration stays correct):
POST /server/web/testfosuser/register/ HTTP/1.1
Host: mywebsite.com
Connection: keep-alive
Content-Length: 229
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/.*;q=0.8
Origin: http://mywebsite.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://mywebsite.com/server/web/testfosuser/register/
Accept-Encoding: gzip, deflate
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: PHPSESSID=xxxxxxxxxxxxxxxxxxxxxxxxx
fos_user_registration_form%5Bemail%5D=bidon%40bidon.com&
fos_user_registration_form%5Busername%5D=bidon&
fos_user_registration_form%5BplainPassword%5D%5Bfirst%5D=bidon&
fos_user_registration_form%5BplainPassword%5D%5Bsecond%5D=bidon
Headers sent with the AJAX request: (NB. added a dot before star in Accept so that the coloration stays correct):
POST /server/web/testfosuser/register HTTP/1.1
Host: mywebsite.com
Connection: keep-alive
Content-Length: 229
Accept: application/json, text/plain, */.*
Origin: http://mywebsite.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36
Content-Type: application/json;charset=UTF-8 application/x-www-form-urlencoded; charset=UTF-8
Referer: http://mywebsite.com/client/
Accept-Encoding: gzip, deflate
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: PHPSESSID=xxxxxxxxxxxxxxxxxxxxxxxxx
fos_user_registration_form%5Bemail%5D=bidonqdsfqsdf%40qsdf&
fos_user_registration_form%5Busername%5D=charles222&
fos_user_registration_form%5BplainPassword%5D%5Bfirst%5D=bidon&
fos_user_registration_form%5BplainPassword%5D%5Bsecond%5D=bidon
I had similar problems and i changed the following inside of the controller:
$user = new User();
$form = $this->createForm(
new UserRegistrationType(),
$user,
array(
'attr' => array('novalidate' => 'novalidate'),
'action' => $this->generateUrl('user_registration')
)
);
Turning of the html5 error bubbles and setting the action URL directly worked for me. If this is not working, show your JS code.
I finally managed to find the correction:
The correct URL is ...../register/ with a final / that I forgot when I did the AJAX request.
However, I'm not sure what are the mechanisms at stake here. The deepest I could go debuging (when using the wrong URL) was in HttpFoundationRequestHandler, where the $request->getMethod() call returned GET (instead of POST), thus not submitting the form.
I'm trying to POST a simple JSON object to a RESTfull server using the following code:
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);
My object is a simple one, it contains a field called {"name" : "MyName"}
The server fails to recognize the request's data.
the request on the network monitor shows this:
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
A working post request looks like this on the network monitor tool:
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"}
Any ideas how can I make the first request perform like the second one?
If you're content type is application/json, then you don't want to use URLVariables for your data:
//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);
Instead, assign the stringified JSON directly to the URLRequest's data property like in the following example:
var urlRequest:URLRequest= new URLRequest("http://localhost:8080/xxx/player/createAccount");
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = JSON.stringify({"name":"MyName"});
var hdr:URLRequestHeader = new URLRequestHeader("Content-type", "application/json");
urlRequest.requestHeaders.push(hdr);
_urlLoader = new URLLoader();
_urlLoader.addEventListener(Event.COMPLETE, onXMLDataLoaded);
_urlLoader.load(urlRequest);
P.S. There is a good tutorial that can help with understanding REST paradigm.