I am able to post to a web-service I wrote in C# from PHP via a CURL request, but I cannot get the request to go through correctly. No matter what I do, the only way that I can get the post to show up is if I json_encode
the form data headers. So my PHP code then ends up like so:
$user = array('id'=>5, 'first_name' => 'First', 'last_name' => 'Last'); $uch = curl_init(); curl_setopt($uch, CURLOPT_URL,"http://localhost:50115/Service1.svc/postUser"); curl_setopt($uch, CURLOPT_POST, 1); curl_setopt($uch, CURLOPT_POSTFIELDS, json_encode("user=" . json_encode($user))); curl_setopt($uch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json' )); curl_setopt($uch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($uch);
When I set the line:
curl_setopt($uch, CURLOPT_POSTFIELDS, json_encode("user=" . json_encode($user)));
to:
curl_setopt($uch, CURLOPT_POSTFIELDS, array("user" => json_encode($user)));
--OR--
curl_setopt($uch, CURLOPT_POSTFIELDS,
http_build_query(array("user" => json_encode($user))));
--OR--
curl_setopt($uch, CURLOPT_POSTFIELDS, json_encode($user));
there is no error in the PHP, the C# service does not return an error (I do have the setting to return exceptions set in the config), and the break-point on the function never gets hit.
On the C# side, I have my interface and service set up like so:
//Interface [OperationContract] [WebInvoke(Method="POST", BodyStyle=WebMessageBodyStyle.Bare, //Any other value, the break-point //will not trigger RequestFormat=WebMessageFormat.Json, UriTemplate = "postUser")] void PostUser(string user); //Service public void PostUser(string user) { var request = user; int i = 5; //Debug set here }
When the break-point hits, I am able to see that user
has the value of:
user={"id":5,"first_name":"First","last_name":"Last"}
What I would like to have is for the value of user
to simply be:
{"id":5,"first_name":"First","last_name":"Last"}
Is it possible to receive my response like this? If so, what do I need to change to accomplish it?
user
actuallyuser={"id":5,"first_name":"First","last_name":"Last"}
, or is that what appears in the debugger? Wouldn'tjson_encode($user)
do the trick? – Timuser
. If I want just the json part, I have to usevar json = user.Split('=')[1];
– Jacob Lambertjson_encode
, it appears (at a glance) thatjson_encode($user)
would do the trick. So you would havecurl_setopt($uch, CURLOPT_POSTFIELDS, json_encode(json_encode($user));
. – Timjson_encode($user)
, the break-point never gets hit and no errors are generated. – Jacob Lambert