如何通过POST方法调用API

时间:2017-05-10 09:57:53

标签: c#

我想在C#中编写一个代码来调用API并通过POST方法传递必要的参数,以便将OTP发送到给定的移动号码并返回请求的响应。 API基本URL(要调用的API):https:/api.example.com/api/sendotp.php 使用这些参数将请求提交到上述API: 验证密钥:146424AvL4aO2EHVS 手机号码:0123456789 OTP:8480 发件人:TDTECH

1 个答案:

答案 0 :(得分:0)

您可以使用.NET的HttpClient类。

private HttpClient Http = new HttpClient();
public async void DoRequest(string authKey, string mobile, string otp, string sender)
{
        var postData = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("Authkey", authKey),
            new KeyValuePair<string, string>("Mobile", mobile),
            new KeyValuePair<string, string>("OTP", otp),
            new KeyValuePair<string, string>("Sender", sender),    
        });
        var response = await Http.PostAsync("https://api.example.com/api/sendotp.php", postData);
        var content = await response.Content.ReadAsStringAsync();
        //Handle content/response.
}