使用Json.NET将Json String POST到远程PHP脚本

时间:2011-01-23 06:27:31

标签: c# php json .net-3.5 post

在将Json字符串发布到PHP Web服务器时遇到异常奇怪的行为。我使用JsonTextWriter对象来创建Json字符串。然后我将Json字符串作为POST请求发送。请参阅评论。代码中的HTML响应返回正确的输出,但在浏览器中查看时,网页显示NULL或数组(0){}。

private void HttpPost(string uri, string parameters)
{
WebRequest webRequest = WebRequest.Create(uri);
webRequest.ContentType = "application/x-www-form-urlencoded"; // <- Should this be "application/json" ?
webRequest.Method = "POST";
byte[] bytes = Encoding.UTF8.GetBytes(parameters);
string byteString = Encoding.UTF8.GetString(bytes);
Stream os = null;
try
{ // Send the Post Data 
    webRequest.ContentLength = bytes.Length;   
    os = webRequest.GetRequestStream();
    os.Write(bytes, 0, bytes.Length);    

    Console.WriteLine(String.Format(@"{0}", byteString));     // <- This matches the Json object
}
catch (WebException ex)
{ //Handle Error }

try
{ // Get the response
    WebResponse webResponse = webRequest.GetResponse();
    if (webResponse == null) { return null; }
    StreamReader sr = new StreamReader(webResponse.GetResponseStream());
    Console.WriteLine(sr.ReadToEnd().Trim());                // <- Server returns string response (full HTML page)
}
catch (WebException ex)
{ //Handle Error }
}  

服务器上的相关PHP代码:

$json = json_encode($_POST);   # Not 'standard way'
var_dump(json_decode($json));

任何建议都将不胜感激。

由于

1 个答案:

答案 0 :(得分:1)

尝试使用“application / json”作为内容类型。此外,如果您可以查看请求正文中发送给服务器的内容,请检查请求日志或执行端口80跟踪。

您还可以通过编写一个快速的JQuery ajax函数来缩小问题的范围 - 无论是C#代码还是PHP代码都是错误的 - 它将一些JSON发送到PHP服务器。从C#代码中隔离PHP代码将告诉您PHP是否至少正常工作。如果是,则问题出在C#代码中。