Can anyone explain me, why I can't reuse WebClient object to send another HTTP POST request?
This code doesn't work:
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
Exception is:
The remote server returned an error: (400) Bad Request.
But if I recreate WebClient object before the second HTTP POST, it works without any issues.
This code works.
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);
The API, which I'm using there - this is Nexmo API.
Thanks.
Once created, we can reuse the builder to instantiate multiple Web Client instances. That helps us avoiding reconfiguring all the client instances. Create WebClient Builder with common configurations. Once this is done, we can reuse the WebClient Builder to create a Web Client.
Method SummarySet the media type of the body, as specified by the Content-Type header. Add a cookie with the given name and value. Copy the given cookies into the entity's cookies map. Perform the request without a request body.
Like PHeiberg stated, WebClient
clears the Headers
after the request is done, so adding them again will make it work.
In answer to LokiSinclair comment about the personal preference to create a new object, I must say that it is not a good practice if you are using an inherited WebClient
that uses Cookies and other relevant functionality that you need to share between requests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With