C#使用PostAsync进行多次请求时,只有首次发送有请求体,后续发送接收方均检测没有请求体而报错。
private async void TwoNetSend(string objectURL, string sendData)
{
string URL = "";
string requestURI = "";
bool bEnable = GetTwoNetParas(out URL, out requestURI);
//bool bEnable = true;
if (bEnable == false)
{
Noter.Write("未配置传输参数", "TwoNetSend");
return;
}
try
{
HttpClient _Client = new HttpClient();
_Client.BaseAddress = new Uri(URL);
_Client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
Dictionary<string, string> paras = new Dictionary<string, string>();
paras.Add("URL", objectURL);
paras.Add("sendData", sendData);
string pc = JsonConvert.SerializeObject(paras);
using (StringContent postContent = new StringContent(pc, Encoding.GetEncoding("GBK"), "application/json"))
{
Noter.Write("传输数据:" + pc, "TwoNetSend");
var response = await _Client.PostAsync(requestURI, postContent);
bool result = response.IsSuccessStatusCode;
Noter.Write("传输状态:" + result.ToString(), "TwoNetSend");
}
_Client.Dispose();
}
catch (Exception ex)
{
Noter.Write(ex.ToString(), "TwoNetSend");
return;
}
}
【以下回答由 GPT 生成】
根据给出的代码来看,只有第一次发送的请求包含了请求体,后续的请求却没有请求体。这是因为代码中使用了HttpClient
类,并在每次发送请求后进行了释放。在这种情况下,由于对象已经被释放,导致后续请求的请求体不会被发送。
为了解决这个问题,我们可以对代码进行一些修改,以确保每次发送请求时都使用同一个HttpClient
对象。
private async Task TwoNetSend(string objectURL, string sendData)
{
string URL = "";
string requestURI = "";
bool bEnable = GetTwoNetParas(out URL, out requestURI);
if (!bEnable)
{
Noter.Write("未配置传输参数", "TwoNetSend");
return;
}
try
{
using (HttpClient _Client = new HttpClient())
{
_Client.BaseAddress = new Uri(URL);
_Client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
Dictionary<string, string> paras = new Dictionary<string, string>();
paras.Add("URL", objectURL);
paras.Add("sendData", sendData);
string pc = JsonConvert.SerializeObject(paras);
using (StringContent postContent = new StringContent(pc, Encoding.GetEncoding("GBK"), "application/json"))
{
Noter.Write("传输数据:" + pc, "TwoNetSend");
var response = await _Client.PostAsync(requestURI, postContent);
bool result = response.IsSuccessStatusCode;
Noter.Write("传输状态:" + result.ToString(), "TwoNetSend");
}
}
}
catch (Exception ex)
{
Noter.Write(ex.ToString(), "TwoNetSend");
return;
}
}
解决方案中的修改部分包括: 1. 将方法签名中的async void
改为async Task
,以便能够在调用方使用await
关键字等待方法完成。 2. 将HttpClient
对象的声明和使用放在了using
语句块中,确保在使用完毕后能够被正确地释放。
通过以上修改,我们可以保证每次发送请求时都使用同一个HttpClient
对象,从而确保每次请求都包含请求体。
【相关推荐】