当前位置: 移动技术网 > IT编程>开发语言>c# > C# consume RestApi

C# consume RestApi

2019年08月30日  | 移动技术网IT编程  | 我要评论
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);
        }
    }
}

 

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网