C# consume RestApi
程序员文章站
2022-08-28 18:07:18
1.RestSharp. Nuget install RestSharp,Newtonsoft.Json. 2.HttpWebRequest 3.HttpClient 4.ServiceStack. Install ServiceStack in Nuget. ......
1.restsharp.
nuget install restsharp,newtonsoft.json.
using system; using restsharp; using newtonsoft.json.linq; namespace dbdll { public class restsharpapi { public static void getwebresonse(string baseurl = "https://api.github.com/repos/restsharp/restsharp/releases") { var client = new restclient(baseurl); irestresponse response = client.execute(new restrequest()); //return the formatted json string from a clumsy json string. var releases = jarray.parse(response.content); console.writeline(releases); } } }
2.httpwebrequest
using newtonsoft.json.linq; using system; using system.io; using system.net; namespace dbdll { public class httpwebrequestdemo { public static void httpwebrequestshow(string baseurl = "https://api.github.com/repos/restsharp/restsharp/releases") { var httprequest = (httpwebrequest)webrequest.create(baseurl); httprequest.method = "get"; httprequest.useragent = "mozilla / 5.0(windows nt 6.1; win64; x64) applewebkit / 537.36(khtml, like gecko) chrome / 58.0.3029.110 safari / 537.36"; httprequest.automaticdecompression = decompressionmethods.gzip | decompressionmethods.deflate; var httpresponse = (httpwebresponse)httprequest.getresponse(); string content = string.empty; using(var responsestream=httpresponse.getresponsestream()) { using(var sr=new streamreader(responsestream)) { content = sr.readtoend(); } } console.writeline(content); } } }
3.httpclient
using system; using system.io; using system.net.http; namespace dbdll { public class httpclientdemo { public static void httpclientshow(string url) { httpclient httpclient = new httpclient(); var response = httpclient.getstringasync(url); console.writeline(response.result); string textfile = directory.getcurrentdirectory() + "//" + "web.txt"; using(streamwriter webwriter=new streamwriter(textfile,true)) { webwriter.writeline(response.result+"\n"); } } } }
4.servicestack.
install servicestack in nuget.
using system; using servicestack; namespace dbdll { public class servicestackdemo { public static void servicestackshow(string url) { var response= url.getjsonfromurl(); console.writeline(response); } } }
上一篇: AMD锐龙首次进驻:微软Surface Laptop 3笔记本预售
下一篇: 我的香皂啊