Skip to main content
 首页 » 编程设计

C#之Json POST 请求已发送但未被 PHP 服务器接收

2024年02月06日11lyhabc

我正在从 C# windowsform 应用程序向托管在 OpenShift (Redhat) 上的 PHP 服务器发送 HTTP 请求。我正在使用带有 Json 数据的 POST 方法。

问题在于:

  • 数据似乎已正确发送(我在 wireshark 中看到数据包)
  • php 脚本正确启动,我在日志中看到收到了 POST 消息
  • 但是没有收到 POST 数据..

这是 C# 代码:

string json = "{\"user\":\"test\"," + 
                "\"n\":\"2\"}"; 
 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://........rhcloud.com/webservices.php"); 
 
request.Method = "POST"; 
request.ContentType = "application/json"; 
request.ContentLength = json.Length; 
 
using (var streamWriter = new StreamWriter(request.GetRequestStream())) 
{ 
    streamWriter.Write(json); 
    streamWriter.Close(); 
 
    var httpResponse = (HttpWebResponse)request.GetResponse(); 
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) 
    { 
         var result = streamReader.ReadToEnd(); 
         Debug.WriteLine("R : " + result); 
    } 
} 

这是 PHP 代码:

echo "Start Saving ! "; 
 
// Handle Posted Data From C# App 
if (isset($_POST) && !empty($_POST)) 
{ 
    echo 'Data Recieved'; 
} 
else 
{ 
  // Error 
  echo 'No POST Data Found'; 
}    

函数总是返回:“开始保存!未找到 POST 数据”。

这是服务器上的日志行:

这是 wireshark 中的行:

有人发现问题了吗?如果我不清楚,请随时告诉我。 拦截数据的可能是Openshift吗?我的 php 文件有问题吗?

请您参考如下方法:

PHP 的 $_POST 不理解 JSON。

你想要的是类似的东西

// Error handling is left as an exercise 
$input = json_decode(file_get_contents('php://input'), true); 

然后您应该能够按照您希望使用 $_POST 的方式使用 $input。参见 json_decode用于转动额外的旋钮。