Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching from HttpWebRequest to HttpClient

I am trying to move change some methods from httpwebrequest to httpclient. I have done most of the work but stuck with this one. Can someone help to achieve this.

string url = someurl;
HttpWebRequest request = CreateRequest(url);

request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;

string body = @"somestring here.";
byte[] postBytes = Encoding.UTF8.GetBytes(body);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();

response = (HttpWebResponse)request.GetResponse();

I need to convert this method using HttpClient.

This is what I have tried.

string url = someurl;
var client = new HttpClient();;

client.DefaultRequestHeaders
      .Accept
      .Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));//ACCEPT header

//request.ContentType = "application/x-www-form-urlencoded";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,url);

string body = @"somestring here...";

var content = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");
request.Content = content;

var ss = client.PostAsync(url,content).Result;
string str2 = await ss.Content.ReadAsStringAsync();

and I am not getting this part to work.

string body = @"somestring here.";
byte[] postBytes = Encoding.UTF8.GetBytes(body);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();
like image 313
Parminder Avatar asked Nov 18 '22 09:11

Parminder


1 Answers

This is the sample client class which I use most of the time. You can use either PostAsync or SendAsync

public class RestClient
{
    public bool IsDisposed { get; private set; }
    public HttpClient BaseClient { get; private set; }

    private readonly string jsonMediaType = "application/json";

    public RestClient(string hostName, string token, HttpClient client)
    {
        BaseClient = client;
        BaseClient.BaseAddress = new Uri(hostName);
        BaseClient.DefaultRequestHeaders.Add("Authorization", token);
    }

    public async Task<string> PostAsync(string resource, string postData)
    {
        StringContent strContent = new StringContent(postData, Encoding.UTF8, jsonMediaType);
        HttpResponseMessage responseMessage = await BaseClient.PostAsync(resource, strContent).ConfigureAwait(false);
        responseMessage.RaiseExceptionIfFailed();
        return await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
    }

    public async Task<string> SendAsync(HttpMethod method, string resource, string token, string postData)
    {
        var resourceUri = new Uri(resource, UriKind.Relative);
        var uri = new Uri(BaseClient.BaseAddress, resourceUri);
        HttpRequestMessage request = new HttpRequestMessage(method, uri);
        request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
        if (!string.IsNullOrEmpty(postData))
        {
            request.Content = new StringContent(postData, Encoding.UTF8, jsonMediaType);
        }

        HttpResponseMessage response = BaseClient.SendAsync(request).Result;
        response.RaiseExceptionIfFailed();
        return await response.Content.ReadAsStringAsync();
    }

    protected virtual void Dispose(bool isDisposing)
    {
        if (IsDisposed)
        {
            return;
        }
        if (isDisposing)
        {
            BaseClient.Dispose();
        }
        IsDisposed = true;
    }

    public virtual void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~RestClient()
    {
        Dispose(false);
    }


}
like image 99
Abhay Avatar answered Dec 21 '22 22:12

Abhay