在C#中使用JSON消费RESTful Web服务
在C#中使用JSON消费RESTful Web服务
这是我目前的代码:\n
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() { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = DATA.Length; using (StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII)) { requestWriter.Write(DATA); } using (WebResponse webResponse = request.GetResponse()) { using (Stream webStream = webResponse.GetResponseStream()) { 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); } } }
\n问题在于我认为异常块被触发了(因为当我移除try-catch时,我会得到一个服务器错误(500)的消息)。但是我没有看到我放在catch块中的Console.Out行。\n我的控制台输出:\n
The thread 'vshost.NotifyLoad' (0x1a20) has exited with code 0 (0x0). The thread '' (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 ' ' (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).
问题的原因是发起的HTTP请求返回了404错误,即资源未找到。解决方法是在发起请求前添加Authorization头部,将token作为Bearer凭证传递。
文章内容如下:
在使用C#消费一个带有JSON的RESTful web服务时,我们需要注意以下几点。首先,我们需要确保使用using语句块来正确地释放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); } } } }
注意,我们需要添加Authorization头部,将token作为Bearer凭证传递。具体代码如下:
request.Headers.Add("Authorization", "Bearer " + token);
这样就可以使用token进行身份验证/登录,并使用GET方法获取数据了。
使用RestSharp和JSON.NET是一个明智的选择。我发现微软的工具集在某些方面还不够完善,可能会出现故障。
另一个支持RestSharp的原因是它可以更容易地进行测试,比WebApi客户端库要容易得多。
对于使用mono的用户来说,RestSharp似乎使用的是System.Net WebRequest API,根据我的经验,它不如.net的实现可靠。(随机的卡死)
这里需要一个示例。
RestSharp的默认JSON反序列化器不如JSON.NET强大。
关于RestSharp需要注意一点。我发现虽然它似乎使用了语义化版本控制,但实际上并没有,当我从一个版本升级到另一个版本时,很多时候会遇到破坏性的更改(接口更改/移除),而版本号表明该更改只是修复bug。
你可以覆盖默认的反序列化器:github.com/restsharp/RestSharp/wiki/Deserialization
缺少示例使得这个帖子不够有用!
我发现RestSharp的反序列化器不支持数组,但对于List来说效果非常好!
请注意,截至我撰写本评论时,RestSharp团队仍然存在套接字耗尽问题:github.com/restsharp/RestSharp/issues/1322
以上是关于如何在C#中使用JSON消费RESTful web服务的一些讨论和建议。使用RestSharp和JSON.NET是一个可行的解决方案,它们提供了更简洁和强大的方式来处理REST服务的调用和响应数据的解析。此外,还注意到RestSharp的一些限制和问题,例如默认的JSON反序列化器的能力不如JSON.NET强大,以及可能会遇到版本升级时的破坏性更改。使用RestSharp和JSON.NET可以提高代码的易用性和健壮性。
问题:如何使用C#和JSON消费一个RESTful web服务?
原因:ASP.NET Web API已经取代了之前提到的WCF Web API。根据微软的最新指南,建议使用Microsoft ASP.NET Web API客户端库来消费RESTful服务。这个库可以通过NuGet包Microsoft.AspNet.WebApi.Client进行安装。
解决方法:首先,在解决方案中添加Microsoft.AspNet.WebApi.Client NuGet包。然后,使用ASP.NET Web API客户端库实现如下代码:
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>().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(); } } }
请注意,在多次请求时,应该重复使用HttpClient实例,而不是创建新的实例。为了更好地管理资源,请使用using语句将HttpClient声明包装起来。
以上是问题“如何使用C#和JSON消费一个RESTful web服务?”的原因和解决方法。如果需要更多详情,请参考微软官方文档《从.NET客户端(C#)调用Web API》和相关的博客文章。