System.Net.HttpClient和cURL没有给出相同的结果

时间:2016-10-30 20:24:59

标签: c# php json curl

我有一个我不明白的问题。

每次我发布一些变量时,我的index.php都在JSON中返回另一个页面,否则返回通用页面。

基本上,它使用以下命令按预期工作:

curl --data "menu=mychoice&group=mygroup" http://localhost/index.php

返回正确的JSON对象(如果mychoice或mygroup无效,则返回通用index.php页面)

我尝试在C#中实现此行为,但如果菜单和组正确,则无法成功检索JSON对象。这是我的代码:

    private async void WebQuery()
    {
         var client = new HttpClient();
         var url = @"http://localhost/index.php";

// not working
         var data = "menu=mymenu&group=mygroup";
         StringContent queryString = new StringContent(data);
         HttpResponseMessage response = await client.PostAsync(url, queryString);

// or, not working too                 
        var postData = new List<KeyValuePair<string, string>>();
        postData.Add(new KeyValuePair<string, string>("menu", "mymenu"));
        postData.Add(new KeyValuePair<string, string>("group", "mygroup"));
        HttpContent queryContent = new FormUrlEncodedContent(postData);
        HttpResponseMessage response = await client.PostAsync(url, queryContent);

        response.EnsureSuccessStatusCode();
        string content = await response.Content.ReadAsStringAsync();
        }

我要么选择HttpContent作为StringContent,要么选择FormUrlEncodedContent,它不起作用。

我的index.php看起来像:

<?php
if (isset($_POST['menu') && isset($_POST['group']))
{
echo json_encode(myarray);
exit;
}
header('Location: generic.php');
?>

我无法理解为什么它使用curl而不是httpClient。有什么提示吗?

精确度:如果我用GET替换POST,它可以按照预期的方式使用HttpClient。

0 个答案:

没有答案