5

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.

Artyom Pranovich
  • 6,814
  • 8
  • 41
  • 60
  • Does remote server return some cookies on your first request? If so, may be `WebClient` maintains cookie container inside itself and it causes second request to fail. – ilyabreev May 27 '15 at 07:56
  • 2
    Personally I'd always create a new object, because you can never know whats been set on the previous one. There's no harm in issuing a `= new WebClient` - At least there wont be any unknown surprises, like this one. – laminatefish May 27 '15 at 08:01
  • I'd love to know why this is happening - could you proxy both requests (using something like Runscope) and send them to me? I'm just Tim at Nexmo. – Tim Lytle Jul 08 '15 at 14:45
  • https://www.runscope.com/docs/sharing shows you how to share a request with someone – John Sheehan Jul 08 '15 at 15:28
  • 5
    I ran into the same problem - the `WebClient` clears the Headers collection after each request. So if you re-add the Accept header it should work to reuse the client instance. – PHeiberg Mar 18 '16 at 09:51
  • 1
    It seems that there is a special case for the Authorization header, which is kept intact for the second request. – stannius Jul 15 '16 at 00:11

1 Answers1

5

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.

Community
  • 1
  • 1
ragnar
  • 1,252
  • 11
  • 18