c#发送POST请求并验证是否能获得返回值返回值返回json然后判断json里code是否为1
使用C#发送POST请求并验证返回值可以使用HttpClient类来实现。以下是一个示例代码:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class Program
{
public static async Task Main(string[] args)
{
string url = "http://example.com/api";
string requestData = "{\"param1\":\"value1\", \"param2\":\"value2\"}";
HttpClient client = new HttpClient();
HttpContent content = new StringContent(requestData);
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
var jsonResponse = JsonConvert.DeserializeObject<dynamic>(responseBody);
int code = jsonResponse.code;
if (code == 1)
{
Console.WriteLine("Code is 1");
}
else
{
Console.WriteLine("Code is not 1");
}
}
else
{
Console.WriteLine("Error: " + response.StatusCode);
}
}
}
请注意,上述示例中的url是要发送POST请求的URL,requestData是请求的数据。根据实际情况修改这两个变量的值。在示例中,我们将返回的JSON字符串解析为dynamic对象,并从中获取code字段的值。然后判断code是否为1,根据结果输出相应的信息。
确保在使用代码之前添加了System.Net.Http和Newtonsoft.Json命名空间的引用
原文地址: http://www.cveoy.top/t/topic/iGS9 著作权归作者所有。请勿转载和采集!