重用 WebClient 对象发送另一个 HTTP 请求

Reusing WebClient object to send another HTTP request

谁能解释一下,为什么我不能重用 WebClient 对象发送另一个 HTTP POST 请求?

此代码不起作用:

var client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string buySmsNumberResult = client.UploadString(ApiBuyUrl, apiBuyParams); //it works fine

//but when I try to send another HTTP POST with the existing WebClient object
string updateSmsNumberResult = client.UploadString(ApiUpdateNumberUrl, apiUpdateParams);
//it throws the exception

例外情况是:

The remote server returned an error: (400) Bad Request.

但是如果我在第二个 HTTP POST 之前重新创建 WebClient 对象,它可以正常工作。

代码有效

var client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string buySmsNumberResult = client.UploadString(ApiBuyUrl, apiBuyParams); 

//recreating of the WebCLient object
client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string updateSmsNumberResult= client.UploadString(ApiUpdateNumberUrl, apiUpdateParams);

我在那里使用的 API - 这是 Nexmo API

谢谢。

所述,WebClient 会在请求完成后清除 Headers,因此再次添加它们将使其生效。

在回答 关于创建新对象的个人偏好的评论时,我必须说,如果您使用继承的 WebClient 并使用 Cookie 和其他对象,这不是一个好习惯您需要在请求之间共享的相关功能。