Today, a lot of Web services are implemented with restful APIs.
For example, Baidu's search promotion API describes the use of REST reason:Rest+json-style API compared to Soap+xml, the advantage is: call more flexible. It is also easier to extend, and the JSON format transmits information about 30% less data than XML and is more efficient. Developers are therefore advised to use RESTful APIs.
Found very many call Rest API network fragmentation data, always can not understand or take effect.
Take a look at the following as an effective reference.
Http://www.makeyuan.com/2014/02/27/1117.html
This article uses the Post method to invoke the Baidu search promotion API. Despite the code mess. But finally succeeded, the following is the code:
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 ());} }
The JSON data section is discovered by execution. When there is no line break before. Use @ to denote a string and a double-argument to represent it in two. will report a data error.
There are several ways to call a linked article:
1. Get by Get method
using System;using System.IO;using System.Net;using System.Text;// Create the web requestHttpWebRequest request = WebRequest.Create("http://developer.yahoo.com/"as HttpWebRequest;// Get responseusingas HttpWebResponse){// Get the response streamnew StreamReader(response.GetResponseStream());// Console application outputConsole.WriteLine(reader.ReadToEnd());}
2. Get the Post method
Using System. Web;URI address = new Uri ("Http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction");Create the Web requesthttpwebrequest request = WebRequest. Create(address) as HttpWebRequest;//SetType to Postrequest. Method="POST";Request. ContentType="application/x-www-form-urlencoded";Create the data we want to sendstring appId ="Yahoodemo";String context ="Italian sculptors and painters of the Renaissance"+"favored the Vir
C # calls the restful API