Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing WebClient object to send another HTTP request

Tags:

c#

.net

http

vonage

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.

like image 962
Artyom Pranovich Avatar asked May 27 '15 07:05

Artyom Pranovich


People also ask

Can I reuse WebClient?

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.

How do I add a custom header in WebClient?

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.


1 Answers

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.

like image 51
ragnar Avatar answered Oct 29 '22 16:10

ragnar