如何在c#中使用WebRequest

时间:2014-01-09 19:30:40

标签: c# .net api webrequest

我试图在下面的链接中使用示例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.Code

        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并发布api。如何使用WebRequest来使用api?

我将首次在.net中使用api

将不胜感激任何帮助。

感谢。

2 个答案:

答案 0 :(得分:3)

看起来您需要在发出请求时将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 :(得分:0)

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

            }