在将 Json 字符串发布到 PHP 网络服务器时,我遇到了异常奇怪的行为。我使用 JsonTextWriter 对象创建 Json 字符串。然后我将 Json 字符串作为 POST 请求发送。请看评论。代码中的 HTML 响应返回正确的输出,但在浏览器中查看时,网页显示 NULL 或 array(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));
如有任何建议,我们将不胜感激。
谢谢
最佳答案
尝试使用“application/json”作为内容类型。此外,检查请求日志,或者如果可以查看请求正文中发送到服务器的内容,则可以执行端口 80 跟踪。
您还可以缩小问题的范围——是 C# 代码还是 PHP 代码有问题——通过编写一个快速的 JQuery ajax 函数将一些 JSON 发送到 PHP 服务器。 PHP 代码与 C# 代码的这种隔离将告诉您 PHP 是否至少正常工作。如果是,则问题出在 C# 代码中。
关于c# - 使用 Json.NET 将 Json 字符串发布到远程 PHP 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4772607/