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

后端 未结 15 1609
面向向阳花
面向向阳花 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 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));
    WebClient syncClient = new WebClient();
    string content = syncClient.DownloadString(url);
    
    using (MemoryStream memo = new MemoryStream(Encoding.Unicode.GetBytes(content)))
    {
        IEnumerable countries = (IEnumerable)serializer.ReadObject(memo);
    }
    
    Console.Read();
    

提交回复
热议问题