C#调用RESTful API

现在很是多的网络服务都用RESTful API来实现。javascript

比方百度的搜索推广API介绍使用Rest缘由:REST+JSON风格的API相比SOAP+XML,优势是:调用更加灵活。也更easy扩展;JSON格式传输信息比XML下降约30%的数据量,效率更高。所以建议开发人员使用REST风格的APIhtml

查找了很是多调用Rest API网络碎片资料,老是没法理解或者生效。java

如下摘一点认为有效果的做为參考吧。web

http://www.makeyuan.com/2014/02/27/1117.htmljson

利用该文中Post方法来调用百度搜索推广的API。尽管代码乱。但是总算成功了,如下便是代码:api

public static void send()
        {
            string url = "https://api.baidu.com/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数据部分。当以前没有换行符的时候。使用@表示字符串并双引號用两个来表示时。会报数据错误。markdown

附上连接的文章的几种调用方式:
一、以Get方式获取网络

using System;
using System.IO;
using System.Net;
using System.Text;

// Create the web request
HttpWebRequest request = WebRequest.Create("http://developer.yahoo.com/") 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());
}

二、以Post方式获取app

using System.Web;

Uri address = new Uri("http://api.search.yahoo.com/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 
posted @ 2017-05-07 08:04  zsychanpin 阅读( ...) 评论( ...) 编辑 收藏
相关文章
相关标签/搜索