我的代码曾经运行良好,这是
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();
}
问题是,
WebClient
已过时,我需要将其转换为HttpClient
我不确定如何将其转换为
HttpClient
...我已经尝试过
var verificationRequest = new HttpClient();
var content = new StringContent(strRequest, Encoding.UTF8, "text/xml");
var response= verificationRequest.PostAsync(AbstractPricing.PaypalWebAddress, content);
//help here please
我不知道最后一点该怎么做 - 如何使用
HttpClient
进行验证
您可以以与 Web 客户端相同的方式构建请求
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()) {
// Set the Content-Type header
httpClient.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded");
// Create the HTTP content
var content = new StringContent(strRequest, Encoding.ASCII);
// 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}");
}
}