Wojciech
Wojciech

Reputation: 39

Convert HttpWebRequest to HttpClient with POST method

I try to convert HttpWebRequest to HttpClient but without success. Can anybody help me?

It is my simple code with HttpWebRequest:

string url = "https://www.somesite.com/Service";
string postData = "text to send";
var data = Encoding.ASCII.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.Proxy = null;
request.AllowAutoRedirect = false;
request.UserAgent = "Mozilla/5.0";
request.ContentType = "text/x-gwt-rpc; charset=UTF-8";
request.Headers.Add("Cookie", SetCookie);//get it after login
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream()); 
string responseText = reader.ReadToEnd();

Upvotes: 1

Views: 1135

Answers (1)

Peter Csala
Peter Csala

Reputation: 22714

I think you can convert you HttpWebRequest based code to HttpClient based like this:

string url = "https://www.somesite.com/Service";
string postData = "text to send";
var data = Encoding.ASCII.GetBytes(postData);
var content = new ByteArrayContent(data);

using var httpHandler = new HttpClientHandler { UseCookies =  false, AllowAutoRedirect = false };
using var client = new HttpClient(httpHandler);
client.DefaultRequestHeaders.Add("UserAgent","Mozilla/5.0");
client.DefaultRequestHeaders.Add("ContentType", "text/x-gwt-rpc; charset=UTF-8");
client.DefaultRequestHeaders.Add("Cookie", SetCookie);

using var requestMessage = new HttpRequestMessage(HttpMethod.Post, url) { Content = content };

var response = await client.SendAsync(requestMessage);
var responseText = await response.Content.ReadAsStringAsync();

Remarks:

  1. Instead of writing the Request's Stream manually you can use the ByteArrayContent abstraction for this. (Related SO topic)
  2. In order to set the cookie(s) manually you have to turn-off the default behaviour. You can do this via the HttpClientHandler's UseCookies. (Related SO topic)
  3. To set the headers manually you can use the HttpClient's DefaultRequestHeaders (Related SO topic)
  4. The counterpart of GetResponse is the SendAsync
  5. Instead of reading the Response's Stream manually you can use the HttpContent's ReadAsStringAsync (Related SO topic)

UPDATE: Include OP's amended code

var content = new StringContent(postData, Encoding.UTF8, "text/x-gwt-rpc");

So, instead of ByteArrayContent StringContent is being used.

Upvotes: 2

Related Questions