这是我到目前为止的代码:

    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;
            StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
            requestWriter.Write(DATA);
            requestWriter.Close();

             try {
                WebResponse webResponse = request.GetResponse();
                Stream webStream = webResponse.GetResponseStream();
                StreamReader responseReader = new StreamReader(webStream);
                string response = responseReader.ReadToEnd();
                Console.Out.WriteLine(response);
                responseReader.Close();
            } catch (Exception e) {
                Console.Out.WriteLine("-----------------");
                Console.Out.WriteLine(e.Message);
            }

        }
    }

问题是我认为异常块正在被触发(因为当我删除try-catch时,我得到一个服务器错误(500)消息。但是我没有看到控制台。我在catch block里放了几行。

我的控制台:

The thread 'vshost.NotifyLoad' (0x1a20) has exited with code 0 (0x0).
The thread '<No Name>' (0x1988) has exited with code 0 (0x0).
The thread 'vshost.LoadReference' (0x1710) has exited with code 0 (0x0).
'ConsoleApplication1.vshost.exe' (Managed (v4.0.30319)): Loaded 'c:\users\l. preston sego iii\documents\visual studio 11\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe', Symbols loaded.
'ConsoleApplication1.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
A first chance exception of type 'System.Net.WebException' occurred in System.dll
The thread 'vshost.RunParkingWindow' (0x184c) has exited with code 0 (0x0).
The thread '<No Name>' (0x1810) has exited with code 0 (0x0).
The program '[2780] ConsoleApplication1.vshost.exe: Program Trace' has exited with code 0 (0x0).
The program '[2780] ConsoleApplication1.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).

当前回答

以下是在c#中调用外部API的几种不同方式(2019年更新)。

.NET的内置方式:

webrequest和WebClient——冗长的api和微软的文档不是很容易理解 HttpClient - . net的最新产品&使用起来比上面提到的简单多了。

免费、开源的NuGet包,坦率地说,它比。net内置客户端有更好的开发体验:

ServiceStack。文本(1000个GitHub星,700万NuGet下载)(*)-快速,轻便和弹性。 RestSharp(6000个GitHub星,2300万NuGet下载)(*)-简单的REST和HTTP API客户端 Flurl (1700 GitHub星,300万NuGet下载)(*)-一个流畅,可移植,可测试的HTTP客户端库

上面所有的包都提供了很棒的开发体验(即简洁、简单的API),并且维护得很好。

(*)截至2019年8月

示例:使用servicstack . text从伪Rest API获取Todo项。 其他库具有非常相似的语法。

class Program
{
    static void Main(string[] args)
    {
        // Fake rest API
        string url = "https://jsonplaceholder.typicode.com/todos/1";

        // GET data from API & map to POCO
        var todo =  url.GetJsonFromUrl().FromJson<Todo>();

        // Print the result to screen
        todo.PrintDump();
    }

    public class Todo
    {
        public int UserId { get; set; }
        public int Id { get; set; }
        public string Title { get; set; }
        public bool Completed { get; set; }
    }

}

在. net核心控制台应用程序中运行上述示例,产生以下输出。

使用NuGet安装这些包

Install-Package ServiceStack.Text, or

Install-Package RestSharp, or

Install-Package Flurl.Http

其他回答

与此无关,我确定,但请使用块包装您的IDisposable对象,以确保适当的处置:

using System;
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);
            }
        }
    }
}

我使用Web API 2.0以这种简单的方式做到了这一点。您可以删除UseDefaultCredentials。我在自己的用例中使用了它。

List<YourObject> listObjects = new List<YourObject>();

string response = "";
using (var client = new WebClient() { UseDefaultCredentials = true })
{
     response = client.DownloadString(apiUrl);
}

listObjects = JsonConvert.DeserializeObject<List<YourObject>>(response);
return listObjects;

在使用。net 4.5或。net Core时调用REST API

我推荐DalSoft。RestClient(注意:是我创建的)。原因是,因为它使用动态类型,您可以在一个流畅的调用中包装所有内容,包括序列化/反序列化。下面是一个工作的PUT示例:

dynamic client = new RestClient("http://jsonplaceholder.typicode.com");

var post = new Post { title = "foo", body = "bar", userId = 10 };

var result = await client.Posts(1).Put(post);

这是可以肯定工作的示例代码。我花了一天的时间来从REST服务中读取一组对象:

RootObject是我从REST服务中读取的对象类型。

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();

以下是在c#中调用外部API的几种不同方式(2019年更新)。

.NET的内置方式:

webrequest和WebClient——冗长的api和微软的文档不是很容易理解 HttpClient - . net的最新产品&使用起来比上面提到的简单多了。

免费、开源的NuGet包,坦率地说,它比。net内置客户端有更好的开发体验:

ServiceStack。文本(1000个GitHub星,700万NuGet下载)(*)-快速,轻便和弹性。 RestSharp(6000个GitHub星,2300万NuGet下载)(*)-简单的REST和HTTP API客户端 Flurl (1700 GitHub星,300万NuGet下载)(*)-一个流畅,可移植,可测试的HTTP客户端库

上面所有的包都提供了很棒的开发体验(即简洁、简单的API),并且维护得很好。

(*)截至2019年8月

示例:使用servicstack . text从伪Rest API获取Todo项。 其他库具有非常相似的语法。

class Program
{
    static void Main(string[] args)
    {
        // Fake rest API
        string url = "https://jsonplaceholder.typicode.com/todos/1";

        // GET data from API & map to POCO
        var todo =  url.GetJsonFromUrl().FromJson<Todo>();

        // Print the result to screen
        todo.PrintDump();
    }

    public class Todo
    {
        public int UserId { get; set; }
        public int Id { get; set; }
        public string Title { get; set; }
        public bool Completed { get; set; }
    }

}

在. net核心控制台应用程序中运行上述示例,产生以下输出。

使用NuGet安装这些包

Install-Package ServiceStack.Text, or

Install-Package RestSharp, or

Install-Package Flurl.Http