IlyaGulya
IlyaGulya

Reputation: 967

Can't send POST in C#

I have the following problem. I have the method that sends json via POST:

public string request (string handler, string data) 
{
    WebRequest request = WebRequest.Create(baseUri + "/?h=" + handler);
    request.Method = "POST";
    request.ContentType = "text/json";

    string json = "json=" + data;
    byte[] bytes = Encoding.ASCII.GetBytes(json);
    request.ContentLength = bytes.Length;

    Stream str = request.GetRequestStream();
    str.Write(bytes, 0, bytes.Length);
    str.Close();

    WebResponse res = request.GetResponse();
    StreamReader sr = new StreamReader(res.GetResponseStream());
    lastResponse = sr.ReadToEnd();
    return lastResponse;
}

When using the method on the server does not come data in POST. As if this code is not executed.

Stream str = request.GetRequestStream();
str.Write(bytes, 0, bytes.Length);
str.Close();

On the server i'm using following php script for debug:

<?php print_r($_POST); ?>

Also tried to write to the stream as follows:

StreamWriter strw = new StreamWriter(request.GetRequestStream());
strw.Write(json);
strw.Close();

The result - a zero response. In response comes an empty array.

Upvotes: 1

Views: 1079

Answers (2)

jamesbar2
jamesbar2

Reputation: 614

Have you thought about using WebClient.UploadValues. Using the NameValueCollection with "json" as the name and JSON data string as the value?

This seems like the easiest way to go. Don't forget you can always add headers and credentials to the WebClient.

Upvotes: 0

vstm
vstm

Reputation: 12537

The Problem is, that PHP does not "recognize" the text/json-content type. And thus does not parse the POST-request-data. You have to use the application/x-www-form-urlencoded content-type and secondly you have to encode the POST-data properly:

// ...
request.ContentType = "application/x-www-form-urlencoded";

string json = "json=" + HttpUtility.UrlEncode(data);
// ...

If you intend to supply the JSON-data directly you can leave the content-type to text/json and pass the data directly as json (without the "json=" part):

string json = data;

But in that case you have to change your script on the PHP-side to directly read the post data:

// on your PHP side:
$post_body = file_get_contents('php://input');
$json = json_decode($post_body);

Upvotes: 1

Related Questions