How do I make calls to a REST API using C#?

后端 未结 15 1607
面向向阳花
面向向阳花 2020-11-22 08:10

This is the code I have so far:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Net.Http;
usi         


        
相关标签:
15条回答
  • 2020-11-22 08:54

    My suggestion would be to use RestSharp. You can make calls to REST services and have them cast into POCO objects with very little boilerplate code to actually have to parse through the response. This will not solve your particular error, but it answers your overall question of how to make calls to REST services. Having to change your code to use it should pay off in the ease of use and robustness moving forward. That is just my two cents though.

    Example:

    namespace RestSharpThingy
    {
        using System;
        using System.Collections.Generic;
        using System.IO;
        using System.Linq;
        using System.Net;
        using System.Reflection;
    
        using RestSharp;
    
        public static class Program
        {
            public static void Main()
            {
                Uri baseUrl = new Uri("https://httpbin.org/");
                IRestClient client = new RestClient(baseUrl);
                IRestRequest request = new RestRequest("get", Method.GET) { Credentials = new NetworkCredential("testUser", "P455w0rd") };
    
                request.AddHeader("Authorization", "Bearer qaPmk9Vw8o7r7UOiX-3b-8Z_6r3w0Iu2pecwJ3x7CngjPp2fN3c61Q_5VU3y0rc-vPpkTKuaOI2eRs3bMyA5ucKKzY1thMFoM0wjnReEYeMGyq3JfZ-OIko1if3NmIj79ZSpNotLL2734ts2jGBjw8-uUgKet7jQAaq-qf5aIDwzUo0bnGosEj_UkFxiJKXPPlF2L4iNJSlBqRYrhw08RK1SzB4tf18Airb80WVy1Kewx2NGq5zCC-SCzvJW-mlOtjIDBAQ5intqaRkwRaSyjJ_MagxJF_CLc4BNUYC3hC2ejQDoTE6HYMWMcg0mbyWghMFpOw3gqyfAGjr6LPJcIly__aJ5__iyt-BTkOnMpDAZLTjzx4qDHMPWeND-TlzKWXjVb5yMv5Q6Jg6UmETWbuxyTdvGTJFzanUg1HWzPr7gSs6GLEv9VDTMiC8a5sNcGyLcHBIJo8mErrZrIssHvbT8ZUPWtyJaujKvdgazqsrad9CO3iRsZWQJ3lpvdQwucCsyjoRVoj_mXYhz3JK3wfOjLff16Gy1NLbj4gmOhBBRb8rJnUXnP7rBHs00FAk59BIpKLIPIyMgYBApDCut8V55AgXtGs4MgFFiJKbuaKxq8cdMYEVBTzDJ-S1IR5d6eiTGusD5aFlUkAs9NV_nFw");
                request.AddParameter("clientId", 123);
    
                IRestResponse<RootObject> response = client.Execute<RootObject>(request);
    
                if (response.IsSuccessful)
                {
                    response.Data.Write();
                }
                else
                {
                    Console.WriteLine(response.ErrorMessage);
                }
    
                Console.WriteLine();
    
                string path = Assembly.GetExecutingAssembly().Location;
                string name = Path.GetFileName(path);
    
                request = new RestRequest("post", Method.POST);
                request.AddFile(name, File.ReadAllBytes(path), name, "application/octet-stream");
                response = client.Execute<RootObject>(request);
                if (response.IsSuccessful)
                {
                    response.Data.Write();
                }
                else
                {
                    Console.WriteLine(response.ErrorMessage);
                }
    
                Console.ReadLine();
            }
    
            private static void Write(this RootObject rootObject)
            {
                Console.WriteLine("clientId: " + rootObject.args.clientId);
                Console.WriteLine("Accept: " + rootObject.headers.Accept);
                Console.WriteLine("AcceptEncoding: " + rootObject.headers.AcceptEncoding);
                Console.WriteLine("AcceptLanguage: " + rootObject.headers.AcceptLanguage);
                Console.WriteLine("Authorization: " + rootObject.headers.Authorization);
                Console.WriteLine("Connection: " + rootObject.headers.Connection);
                Console.WriteLine("Dnt: " + rootObject.headers.Dnt);
                Console.WriteLine("Host: " + rootObject.headers.Host);
                Console.WriteLine("Origin: " + rootObject.headers.Origin);
                Console.WriteLine("Referer: " + rootObject.headers.Referer);
                Console.WriteLine("UserAgent: " + rootObject.headers.UserAgent);
                Console.WriteLine("origin: " + rootObject.origin);
                Console.WriteLine("url: " + rootObject.url);
                Console.WriteLine("data: " + rootObject.data);
                Console.WriteLine("files: ");
                foreach (KeyValuePair<string, string> kvp in rootObject.files ?? Enumerable.Empty<KeyValuePair<string, string>>())
                {
                    Console.WriteLine("\t" + kvp.Key + ": " + kvp.Value);
                }
            }
        }
    
        public class Args
        {
            public string clientId { get; set; }
        }
    
        public class Headers
        {
            public string Accept { get; set; }
    
            public string AcceptEncoding { get; set; }
    
            public string AcceptLanguage { get; set; }
    
            public string Authorization { get; set; }
    
            public string Connection { get; set; }
    
            public string Dnt { get; set; }
    
            public string Host { get; set; }
    
            public string Origin { get; set; }
    
            public string Referer { get; set; }
    
            public string UserAgent { get; set; }
        }
    
        public class RootObject
        {
            public Args args { get; set; }
    
            public Headers headers { get; set; }
    
            public string origin { get; set; }
    
            public string url { get; set; }
    
            public string data { get; set; }
    
            public Dictionary<string, string> files { get; set; }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 08:59

    Unrelated, I'm sure, but do wrap your IDisposable objects in using blocks to ensure proper disposal:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System;
    using System.Web;
    using System.Net;
    using System.IO;
    
    namespace ConsoleProgram
    {
        public class Class1
        {
            private const string URL = "https://sub.domain.com/objects.json?api_key=123";
            private const string DATA = @"{""object"":{""name"":""Name""}}";
    
            static void Main(string[] args)
            {
                Class1.CreateObject();
            }
    
            private static void CreateObject()
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
                request.Method = "POST";
                request.ContentType = "application/json";
                request.ContentLength = DATA.Length;
                using (Stream webStream = request.GetRequestStream())
                using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
                {
                    requestWriter.Write(DATA);
                }
    
                try
                {
                    WebResponse webResponse = request.GetResponse();
                    using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
                    using (StreamReader responseReader = new StreamReader(webStream))
                    {
                        string response = responseReader.ReadToEnd();
                        Console.Out.WriteLine(response);
                    }
                }
                catch (Exception e)
                {
                    Console.Out.WriteLine("-----------------");
                    Console.Out.WriteLine(e.Message);
                }
    
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 09:00
        var TakingRequset = WebRequest.Create("http://xxx.acv.com/MethodName/Get");
        TakingRequset.Method = "POST";
        TakingRequset.ContentType = "text/xml;charset=utf-8";
        TakingRequset.PreAuthenticate = true;
    
        //---Serving Request path query
         var PAQ = TakingRequset.RequestUri.PathAndQuery;
    
        //---creating your xml as per the host reqirement
        string xmlroot=@"<root><childnodes>passing parameters</childnodes></root>";
        string xmlroot2=@"<root><childnodes>passing parameters</childnodes></root>";
    
        //---Adding Headers as requested by host 
        xmlroot2 = (xmlroot2 + "XXX---");
        //---Adding Headers Value as requested by host 
      //  var RequestheaderVales = Method(xmlroot2);
    
        WebProxy proxy = new WebProxy("XXXXX-----llll", 8080);
        proxy.Credentials = new NetworkCredential("XXX---uuuu", "XXX----", "XXXX----");
        System.Net.WebRequest.DefaultWebProxy = proxy;
    
    
        // Adding The Request into Headers
        TakingRequset.Headers.Add("xxx", "Any Request Variable ");
        TakingRequset.Headers.Add("xxx", "Any Request Variable");
    
        byte[] byteData = Encoding.UTF8.GetBytes(xmlroot);
        TakingRequset.ContentLength = byteData.Length;
    
        using (Stream postStream = TakingRequset.GetRequestStream())
        {
            postStream.Write(byteData, 0, byteData.Length);
            postStream.Close();
        }
    
    
    
        StreamReader stredr = new StreamReader(TakingRequset.GetResponse().GetResponseStream());
        string response = stredr.ReadToEnd();
    
    0 讨论(0)
  • 2020-11-22 09:01

    The ASP.NET Web API has replaced the WCF Web API previously mentioned.

    I thought I'd post an updated answer since most of these responses are from early 2012, and this thread is one of the top results when doing a Google search for "call restful service C#".

    Current guidance from Microsoft is to use the Microsoft ASP.NET Web API Client Libraries to consume a RESTful service. This is available as a NuGet package, Microsoft.AspNet.WebApi.Client. You will need to add this NuGet package to your solution.

    Here's how your example would look when implemented using the ASP.NET Web API Client Library:

    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Net.Http.Headers;
    
    namespace ConsoleProgram
    {
        public class DataObject
        {
            public string Name { get; set; }
        }
    
        public class Class1
        {
            private const string URL = "https://sub.domain.com/objects.json";
            private string urlParameters = "?api_key=123";
    
            static void Main(string[] args)
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(URL);
    
                // Add an Accept header for JSON format.
                client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
    
                // List data response.
                HttpResponseMessage response = client.GetAsync(urlParameters).Result;  // Blocking call! Program will wait here until a response is received or a timeout occurs.
                if (response.IsSuccessStatusCode)
                {
                    // Parse the response body.
                    var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result;  //Make sure to add a reference to System.Net.Http.Formatting.dll
                    foreach (var d in dataObjects)
                    {
                        Console.WriteLine("{0}", d.Name);
                    }
                }
                else
                {
                    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                }
    
                // Make any other calls using HttpClient here.
    
                // Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous.
                client.Dispose();
            }
        }
    }
    

    If you plan on making multiple requests, you should re-use your HttpClient instance. See this question and its answers for more details on why a using statement was not used on the HttpClient instance in this case: Do HttpClient and HttpClientHandler have to be disposed between requests?

    For more details, including other examples, see Call a Web API From a .NET Client (C#)

    This blog post may also be useful: Using HttpClient to Consume ASP.NET Web API REST Services

    0 讨论(0)
  • 2020-11-22 09:01

    This is example code that works for sure. It took me a day to make this to read a set of objects from a REST service:

    RootObject is the type of the object I'm reading from the REST service.

    string url = @"http://restcountries.eu/rest/v1";
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(IEnumerable<RootObject>));
    WebClient syncClient = new WebClient();
    string content = syncClient.DownloadString(url);
    
    using (MemoryStream memo = new MemoryStream(Encoding.Unicode.GetBytes(content)))
    {
        IEnumerable<RootObject> countries = (IEnumerable<RootObject>)serializer.ReadObject(memo);
    }
    
    Console.Read();
    
    0 讨论(0)
  • 2020-11-22 09:02

    Please use the below code for your REST API request:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Text;
    using System.Json;
    
    namespace ConsoleApplication2
    {
        class Program
        {
            private const string URL = "https://XXXX/rest/api/2/component";
            private const string DATA = @"{
                ""name"": ""Component 2"",
                ""description"": ""This is a JIRA component"",
                ""leadUserName"": ""xx"",
                ""assigneeType"": ""PROJECT_LEAD"",
                ""isAssigneeTypeValid"": false,
                ""project"": ""TP""}";
    
            static void Main(string[] args)
            {
                AddComponent();
            }
    
            private static void AddComponent()
            {
                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                client.BaseAddress = new System.Uri(URL);
                byte[] cred = UTF8Encoding.UTF8.GetBytes("username:password");
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    
                System.Net.Http.HttpContent content = new StringContent(DATA, UTF8Encoding.UTF8, "application/json");
                HttpResponseMessage messge = client.PostAsync(URL, content).Result;
                string description = string.Empty;
                if (messge.IsSuccessStatusCode)
                {
                    string result = messge.Content.ReadAsStringAsync().Result;
                    description = result;
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题