【问题标题】:PostAsJsonAsync POST variables don't arrive at Flight PHP REST serverPostAsJsonAsync POST 变量未到达 Flight PHP REST 服务器
【发布时间】:2014-11-17 20:23:54
【问题描述】:

我设置了 Flight PHP REST 服务器。 在 1 个端点,它需要 POST 数据,并根据其中一个 POST 数据从数据库中检索一些数据并将其作为 JSON 返回。

当我在 Chrome 中使用 Postman REST 扩展时,我看到了正确的结果。但是当我使用我的 C# 应用程序进行调用时,返回的 json 为 null,因为 $_POST 似乎为空。

这是我的航班 index.php:

Flight::route('POST /getText', function(){  
  // Create a new report class:
  $reportText = new ReportText;
  $theText = $reportText->ParsePost($_POST);
  if ($theText == null)
  {
    echo null;
  }
  else
  {
    echo json_encode($theText);
  }        
});

这是我的 ParsePost:

public function ParsePost($PostDictionary)
{
    $textArray = null;
    foreach ($PostDictionary as $key => $value)
    {
        if (!empty($value))
        {
            list($tmp, $id) = explode("_", $key);
            $text = $this->geFooWithText($id);
            $textArray[$key] = "bar";
        }
    }

    return $textArray;
}

这是我的 C# 部分:

private static async Task RunAsyncPost(string requestUri)
{
    using (var client = new HttpClient())
    {
        // Send HTTP requests
        client.BaseAddress = new Uri("myUrl");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        try
        {
            // HTTP POST
            var response = await client.PostAsJsonAsync(requestUri, new { question_8 = "foo", question_9 = "bar" });
            response.EnsureSuccessStatusCode(); // Throw if not a success code.
            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();
                if (string.IsNullOrEmpty(json))
                {
                    throw new ArgumentNullException("json", @"Response from the server is null");    
                }

                var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

                foreach (var kvp in dictionary)
                {
                    Debug.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
                }
            }
        }
        catch (HttpRequestException e)
        {
            // Handle exception.
            Debug.WriteLine(e.ToString());
            throw;
        }
    }
}

这是邮递员的回复:

{
  "question_8": "foo",
  "question_9": "bar"
}

似乎我在使用 C# 的通话中遗漏了一些东西。

[更新]

在这篇文章 (Unable to do a HTTP POST to a REST service passing json through C#) 中似乎出现了同样的问题。 建议使用 Fiddler。

使用 Postman 和 x-www-form-urlencoded:

POST http://myHost/api/getText HTTP/1.1
Host: myHost
Connection: keep-alive
Content-Length: 29
Cache-Control: no-cache
Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: */*
Accept-Encoding: gzip,deflate
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4

question_8=foo&question_9=bar

使用 Postman 和表单数据:

POST http://myHost/api/getText HTTP/1.1
Host: myHost
Connection: keep-alive
Content-Length: 244
Cache-Control: no-cache
Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryvb4wmaP4KooT6TFu
Accept: */*
Accept-Encoding: gzip,deflate
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4

------WebKitFormBoundaryvb4wmaP4KooT6TFu
Content-Disposition: form-data; name="question_8"

foo
------WebKitFormBoundaryvb4wmaP4KooT6TFu
Content-Disposition: form-data; name="question_9"

bar
------WebKitFormBoundaryvb4wmaP4KooT6TFu--

使用我的 C# 应用程序:

POST http://myHost/api/getText/ HTTP/1.1
Accept: application/json
Content-Type: application/json; charset=utf-8
Host: myHost
Content-Length: 50
Expect: 100-continue
Connection: Keep-Alive

{"question_8":"foo","question_9":"bar"}

C# 应用程序以不同的方式清楚地发送它。

【问题讨论】:

    标签: c# json rest dotnet-httpclient flightphp


    【解决方案1】:

    我找到了问题。

    因为我使用client.PostAsJsonAsync(),所以 POST 数据以 json 格式发送,正如您在 Fiddler 中看到的那样。

    PHP 不希望 POST 数据为 json 格式。 要读取该数据,我需要在我的 PHP 文件中使用 $data = file_get_contents('php://input');

    现在我有了我的键和值,我可以继续吗?看起来 PHP 需要一个 $_JSON 变量;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多