如何在c#中使用WebRequest

问题描述 投票:0回答:2

我正在尝试使用下面链接中的示例 API 调用; 请检查链接:

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

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

systemDate

  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();
     }
    
  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";
    

但是我不知道我通过上面的代码是否正确使用了API?

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

如何获取 API 并将其发布到 Sendloop,以及如何使用

WebRequest
使用 API?

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

任何帮助将不胜感激。

谢谢。

c# .net webrequest
2个回答
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();
}

1
投票
    string userAuthenticationURI = 
    "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+ originZip + 
    "&destinations="+ DestinationZip + "&units=imperial&language=en- 
     EN&sensor=false&key=Your API Key";
            if (!string.IsNullOrEmpty(userAuthenticationURI))
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(userAuthenticationURI);
                request.Method = "GET";
                request.ContentType = "application/json";
                WebResponse response = request.GetResponse();
                var responseString = new 
StreamReader(response.GetResponseStream()).ReadToEnd();
                dynamic obj = JsonConvert.DeserializeObject(responseString);

            }
© www.soinside.com 2019 - 2024. All rights reserved.