如何发送发帖请求?

时间:2019-06-13 22:29:38

标签: asp.net c json web-services post

如何在C#中使用Web Post服务?我用POSTMAN进行了测试,得到了响应数据,但是在.net中,我的响应为空。在PostMan中效果很好。问题在于如何格式化正文内容并将其发送。

            string idop = "";
            List<ProductJSON> listProductsJSON = new List<ProductJSON>();
            List<List<string>> productJSON = new List<List<string>>();

            List<string> products = new List<string>();
            products.Add("4");
            products.Add("5");
            products.Add("30.2");
            products.Add("1");
            products.Add("0");
            products.Add("4");
            productJSON.Add(products);

using (var client = new HttpClient())
            {
                var res = client.PostAsync("http://xyz.cti.lat/sant2/webservices/edd.php",
                  new StringContent(JsonConvert.SerializeObject(
                    new {
                        a = "pCatlog",
                        cnal = "RED",
                        tpo = "2",
                        fpago = "DETO",
                        pgdo = "0",
                        rc = "13123",
                        local = "BACK",
                        localorg = "BACK",
                        raz = "PPPPPP",
                        dir_ruc = "name",
                        log = "CREAVIR",
                        not = "DETO2",
                        del = "0",
                        dir = "",
                        ubi = "",
                        refe = "",
                        prod = productJSON
                    }),
                    Encoding.UTF8, "application/json")));

                try
                {
                    res.Result.EnsureSuccessStatusCode();
                    var x = res;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }

1 个答案:

答案 0 :(得分:0)

您可以在try块中尝试此代码吗?

if (res.IsCompleted)
{
    var result = res.Result;
    var response = result.Content.ReadAsStringAsync();
    var data = response.Result;
}

理想的情况是将其声明为异步方法,并使用await操作获取结果,如下所示。

var res = await client.PostAsync(<url>, <string_content>);         
var result = await res.Content.ReadAsStringAsync();