使用HttpClient的POST数据

时间:2018-09-28 00:38:48

标签: c# json httpclient httpcontent

我正在尝试使用HttpClient将数据发布到Web,但是我无法成功。

这是我的JSON网络API

{
    "Categories":[
        {
            "CategoryID":1,
            "Category":"Category 1"
        },
        {
            "CategoryID":2,
            "Category":"Category 2"
        }
    ]
}

我将类别数据发送到Web,我的Web开发人员在json上方向我发送了将数据从Winform发送到Web

这是我的代码

IEnumerable<KeyValuePair<string, string>> paramt = new List<KeyValuePair<string, string>>()
                {
                    new KeyValuePair<string,string>("CategoryID","1"),
                    new KeyValuePair<string,string>("Category","Pizza")
                };
                HttpContent q = new FormUrlEncodedContent(paramt);
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.BaseAddress = new Uri(url);
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", api);
                    HttpResponseMessage response = client.PostAsync("api/categories", q).Result;
 }

对不起,我的英语主持人请更新我的问题

1 个答案:

答案 0 :(得分:1)

感谢@John在您的帮助下,我做到了

public class CategoryItem
        {
            public int CategoryID { get; set; }
            public string Category { get; set; }
        }

        public class CategoriesRoot
        {
            public IList<CategoryItem> Categories { get; set; }
        }

         var tmp = new CategoriesRoot
                {
                    Categories = new List<CategoryItem> {
                    new CategoryItem { CategoryID = 1, Category = "Pizza" }
                }
                };

                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.BaseAddress = new Uri(url);
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", api);
                    HttpResponseMessage response = client.PostAsJsonAsync("api/categories", tmp).Result;
                    }