c#用HttpWebRequest发送POST请求并验证是否能获得返回值返回值返回json然后判断json里code是否为1
以下是使用C#的HttpWebRequest发送POST请求并验证返回值的示例代码:
using System;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main(string[] args)
{
string url = "http://example.com/api";
string postData = "{\"param1\": \"value1\", \"param2\": \"value2\"}";
string responseJson = SendPostRequest(url, postData);
int code = GetCodeFromJson(responseJson);
if (code == 1)
{
Console.WriteLine("Code is 1");
}
else
{
Console.WriteLine("Code is not 1");
}
}
public static string SendPostRequest(string url, string postData)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
byte[] dataBytes = Encoding.UTF8.GetBytes(postData);
request.ContentLength = dataBytes.Length;
using (Stream requestBody = request.GetRequestStream())
{
requestBody.Write(dataBytes, 0, dataBytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseBody = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseBody, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
}
public static int GetCodeFromJson(string json)
{
JObject jsonObject = JObject.Parse(json);
return (int)jsonObject["code"];
}
}
在上面的代码中,url是要发送POST请求的API的URL,postData是要发送的JSON数据。SendPostRequest方法发送POST请求并返回API的响应。GetCodeFromJson方法从返回的JSON中提取code值并返回。
你可以根据实际情况修改url和postData的值,并根据code的值来进行相应的处理
原文地址: https://www.cveoy.top/t/topic/iGWX 著作权归作者所有。请勿转载和采集!