5

谁能解释一下,为什么我不能重用 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

例外是:

远程服务器返回错误:(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);

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

谢谢。

4

1 回答 1

5

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

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

于 2016-05-17T19:39:31.343 回答