如何在c#中使用WebRequest

use*_*063 2 .net c# api webrequest

我正在尝试在下面的链接中使用示例 api 调用,请检查链接

http://sendloop.com/help/article/api-001/getting-started

我的帐户是“code5”,所以我尝试了 2 个代码来获取系统日期。

1. 代码

        var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
        request.ContentType = "application/json; charset=utf-8";

        string text;
        var response = (HttpWebResponse)request.GetResponse();

        using (var sr = new StreamReader(response.GetResponseStream()))
        {
            text = sr.ReadToEnd();
        }
Run Code Online (Sandbox Code Playgroud)

2.代码

        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
        httpWebRequest.Method = WebRequestMethods.Http.Get;
        httpWebRequest.Accept = "application/json";
Run Code Online (Sandbox Code Playgroud)

但我不知道我通过上面的代码正确使用了 api 吗?

当我使用上面的代码时,我看不到任何数据或任何东西。

我如何获取 api 并将其发布到 Sendloop。我如何通过使用 WebRequest 来使用 api?

我将第一次在 .net 中使用 api 所以

任何帮助将不胜感激。

谢谢。

Cam*_*ker 5

看起来您需要在发出请求时将 API 密钥发布到端点。否则,您将无法通过身份验证,并且将返回空响应。

要发送 POST 请求,您需要执行以下操作:

var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";

string postData = "APIKey=xxxx-xxxxx-xxxxx-xxxxx-xxxxx";

request.Method = "POST";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(data, 0, data.Length); // Send the data.
newStream.Close();

string text;
var response = (HttpWebResponse)request.GetResponse();

using (var sr = new StreamReader(response.GetResponseStream()))
{
    text = sr.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)