C#调⽤RESTfulAPI
如今⾮常多的⽹络服务都⽤RESTful API来实现。
⽐⽅百度的搜索推⼴API介绍使⽤Rest原因:REST+JSON风格的API相⽐SOAP+XML,优点是:调⽤更加灵活。也更easy扩展;JSON格式传输信息⽐XML降低约30%的数据量,效率更⾼。因此建议开发⼈员使⽤REST风格的API。
查了⾮常多调⽤Rest API⽹络碎⽚资料,总是⽆法理解或者⽣效。
以下摘⼀点认为有效果的作为參考吧。
利⽤该⽂中Post⽅法来调⽤百度搜索推⼴的API。尽管代码乱。可是总算成功了,以下即是代码:
public static void send()
{
string url = "api.baidu/json/sms/v3/AccountService/getAccountInfo";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
string data = "{\n\"header\": {\n\"token\": \"30xxx6aaxxx93ac8cxx8668xx39xxxx\",\n\"username\": \"jdads\",\n\"password\": \"liuqiangdong2010\",\n\"action\": \"\"\n},\n\"body\": {}\n}";            byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
request.ContentLength = byteData.Length;
using(Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
using(HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
Console.WriteLine(reader.ReadToEnd());
}
}
通过执⾏,发现json数据部分。当之前没有换⾏符的时候。使⽤@表⽰字符串并双引號⽤两个来表⽰时。会报数据错误。
附上链接的⽂章的⼏种调⽤⽅式:
1、以Get⽅式获取
using System;
using System.IO;
using System.Net;
using System.Text;
// Create the web request
HttpWebRequest request = WebRequest.Create("developer.yahoo/") as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(reader.ReadToEnd());
restful接口调用实例
}
2、以Post⽅式获取
using System.Web;
Uri address = new Uri("api.search.yahoo/ContentAnalysisService/V1/termExtraction");
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Create the data we want to send
string appId = "YahooDemo";
string context = "Italian sculptors and painters of the renaissance"
+ "favored the Vir

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。