1

次の問題があります。POSTを介してjsonを送信するメソッドがあります。

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;
}

サーバーでこのメソッドを使用すると、POSTにデータが送信されません。このコードが実行されていないかのように。

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

サーバーでは、デバッグに次のphpスクリプトを使用しています。

<?php print_r($_POST); ?>

また、次のようにストリームに書き込もうとしました。

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

結果-ゼロ応答。それに応じて、空の配列が来ます。

4

2 に答える 2

1

text/json問題は、PHPが-contentタイプを「認識」しないことです。したがって、POST-request-dataは解析されません。application/x-www-form-urlencodedcontent-typeを使用する必要があり、次にPOSTデータを適切にエンコードする必要があります。

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

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

JSONデータを直接提供する場合は、content-typeをそのままにして、データを( "json ="部分なしで)text/json直接渡すことができます。json

string json = data;

ただし、その場合、投稿データを直接読み取るには、PHP側でスクリプトを変更する必要があります。

// on your PHP side:
$post_body = file_get_contents('php://input');
$json = json_decode($post_body);
于 2012-07-31T05:43:18.860 に答える
0

WebClient.UploadValuesの使用について考えたことはありますか。名前として「json」、値としてJSONデータ文字列を指定してNameValueCollectionを使用しますか?

これが最も簡単な方法のようです。WebClientにはいつでもヘッダーとクレデンシャルを追加できることを忘れないでください。

于 2012-07-31T05:43:59.967 に答える