本文介绍了如何在 C# 中使用 WebRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'am trying to use example api call in below link please check link

http://sendloop.com/help/article/api-001/入门

我的帐户是code5",所以我尝试了 2 个代码来获取 systemDate.

My account is "code5" so i tried 2 codes to get 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 吗?

But i don't know that i use correctly api by above codes ?

当我使用上述代码时,我看不到任何数据或任何东西.

When i use above codes i don't see any data or anything.

我如何获取和发布 api 到 Sendloop.我如何通过使用 WebRequest 来使用 api?

How can i get and post api to Sendloop.And how can i use api by using WebRequest ?

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

I will use api first time in .net so

我们将不胜感激.

谢谢.

推荐答案

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

It looks like you need to post your API key to the endpoint when making requests. Otherwise, you will not be authenticated and it will return an empty response.

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

To send a POST request, you will need to do something like this:

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

这篇关于如何在 C# 中使用 WebRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:23
查看更多