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

Art*_*ich 5 .net c# http nexmo

任何人都可以解释一下,为什么我不能重用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
Run Code Online (Sandbox Code Playgroud)

例外情况是:

远程服务器返回错误:(400)错误请求.

但是如果我在第二次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);
Run Code Online (Sandbox Code Playgroud)

API,我在那里使用 - 这是Nexmo API.

谢谢.

rag*_*nar 5

就像PHeiberg所说,在请求完成后WebClient清除它Headers,所以再次添加它们将使它工作.

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