Search code examples
c#paypaldotnet-httpclient

Consuming Rest API with C# and HttpClient


My code used to work fine which is

var verificationRequest2 = WebRequest.Create(AbstractPricing.PaypalWebAddress);
verificationRequest2.Method = "POST";
verificationRequest2.ContentType = "application/x-www-form-urlencoded";

var strRequest = "cmd=_notify-validate&" + ipnContext.RequestBody;
verificationRequest2.ContentLength = strRequest.Length;

using (var writer = new StreamWriter(verificationRequest2.GetRequestStream(), Encoding.ASCII))
{
    writer.Write(strRequest);
}

using (var reader = new StreamReader(verificationRequest2.GetResponse().GetResponseStream()))
{
    ipnContext.Verification = reader.ReadToEnd();
}

The issue is, WebClient is obsolete and I need to convert this to HttpClient

I am unsure how to convert this to HttpClient... I have tried

var verificationRequest = new HttpClient();
var content = new StringContent(strRequest, Encoding.UTF8, "text/xml");
var response= verificationRequest.PostAsync(AbstractPricing.PaypalWebAddress, content);
//help here please

I don't know how to do that last bit - how do I get the verification using HttpClient


Solution

  • You can construct the request in the very same fashion, as the webclient

    class AbstractPricing {
      // Replace this with the actual PayPal web address
      public static string PaypalWebAddress {
        get;
      } = "https://www.example.com/paypal-endpoint";
    }
    
    class IpnContext {
      public string RequestBody {
        get;
        set;
      }
      public string Verification {
        get;
        set;
      }
    }
    
    // Actual code here, previous code just for testing
    var paypalWebAddress = AbstractPricing.PaypalWebAddress;
    var strRequest = "cmd=_notify-validate&" + ipnContext.RequestBody;
    
    using (HttpClient httpClient = new HttpClient())
    {
        // Create the HTTP content with the correct content type
        var content = new StringContent(strRequest, Encoding.ASCII, "application/x-www-form-urlencoded");
    
        // Make the POST request
        HttpResponseMessage response = await httpClient.PostAsync(paypalWebAddress, content);
    
        // Check if the request was successful
        if (response.IsSuccessStatusCode)
        {
            // Read the response content
            ipnContext.Verification = await response.Content.ReadAsStringAsync();
        }
        else
        {
            // Handle the error, e.g., log or throw an exception
            Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
        }
    
        // do something with ipnContext here
    }