客户要求以post的方式将参数以接送格式传递到body中,下面是网上搜到的代码,未做验证
string url="http://........";
ImplantAgentProtectQueryDTO dto = new ImplantAgentProtectQueryDTO();
dto.isProtect = isProtect;
dto.newcode = newcode;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
string strContent = JsonSerializer.Searializer(dto); //序列化为字符串,可以使用自己项目中封装的json方法
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
{
dataStream.Write(strContent);
dataStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
retString = reader.ReadToEnd();
return retString;
下面的是百度AI生成的代码
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
class Program
{
static async Task Main(string[] args)
{
var json = new { /* 定义你的JSON结构 */ };
var jsonContent = JsonConvert.SerializeObject(json);
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, "你的URL");
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "你的Token");
request.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
var response = await client.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
}
}
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
class Program
{
static async Task Main(string[] args)
{
using (var client = new HttpClient())
{
// 设置请求的URL
var url = "http://example.com/api/resource";
// 准备要发送的数据
var jsonData = new { /* 填写你的JSON结构 */ };
var jsonContent = JsonConvert.SerializeObject(jsonData);
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
// 添加Token到请求头
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "your_token_here");
// 发送POST请求
var response = await client.PostAsync(url, content);
// 确保请求成功
response.EnsureSuccessStatusCode();
// 读取并打印响应内容
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
}
}