如何在C#中使用Web Post服务?我用 POSTMAN 做了测试,得到了响应数据,但在 .net 中我的响应是空的。它在 PostMan 中效果很好。问题是如何格式化Body Content并发送。
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());
}
}
最佳答案
你能在 try block 中尝试这段代码吗?
if (res.IsCompleted)
{
var result = res.Result;
var response = result.Content.ReadAsStringAsync();
var data = response.Result;
}
理想的情况是将其声明为异步方法并使用等待操作来获取结果,如下所示。
var res = await client.PostAsync(<url>, <string_content>);
var result = await res.Content.ReadAsStringAsync();
关于asp.net - 如何发送post请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56589305/