这是我到目前为止的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Net.Http;
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;
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块中的Console.Out行 .
我的控制台:
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).
我正在使用Visual Studio 2011 Beta和.NET 4.5 Beta .
12 回答
ASP.Net Web API已经取代了之前提到的WCF Web API .
我想我会发布一个更新的答案,因为大多数答案都是从2012年初开始的,这个帖子是Google搜索“call restful service c#”时的最佳结果之一 .
Microsoft目前的指导是使用Microsoft ASP.NET Web API客户端库来使用RESTful服务 . 它可以作为NuGet包使用,Microsoft.AspNet.WebApi.Client . 您需要将此NuGet包添加到您的解决方案中 .
以下是使用ASP.Net Web API客户端库实现时您的示例的外观:
如果您计划发出多个请求,则应重新使用HttpClient实例 . 有关在这种情况下HttpClient实例上未使用using语句的原因的更多详细信息,请参阅此问题及其答案:Do HttpClient and HttpClientHandler have to be disposed?
有关更多详细信息,包括其他示例,请转到此处:http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client
此博文可能也很有用:http://johnnycode.com/2012/02/23/consuming-your-own-asp-net-web-api-rest-service/
我的建议是使用RestSharp . 您可以调用REST服务并将它们转换为POCO对象,只需很少的样板代码即可实际解析响应 . 这不会解决您的特定错误,但会回答您关于如何调用REST服务的整体问题 . 必须更改您的代码才能使用它,这应该会在易用性和稳健性方面取得进展 . 这只是我的2美分
不相关,我敢肯定,但是要将
IDisposable
对象包装在using
块中以确保正确处理:请使用以下代码来获取REST api请求
Update for calling a REST API when using .NET 4.5 or .NET Core
我建议DalSoft.RestClient(我创建它的警告) . 原因是因为它使用动态类型,您可以在一个流畅的调用中包含所有内容,包括序列化/反序列化 . 以下是一个有效的PUT示例:
查看改装以从.net拨打休息服务 . 我发现它很容易使用:https://github.com/paulcbetts/refit
GET:
POST:
注意:为了序列化和绝望JSON,我使用了Newtonsoft.Json NuGet包 .
这是一个可行的示例代码 . 我花了一天时间才能从Rest服务中读取一组对象:
RootObject是从休息服务中读取的对象的类型 .
由于您使用的是Visual Studio 11 Beta,因此您需要使用最新且最好的 . 新的Web Api包含此类 .
见HttpClient:http://wcf.codeplex.com/wikipage?title=WCF%20HTTP
我用这个简单的方式做了它,使用web Api 2.0 . 您可以删除UseDefaultCredentials . 我将它用于我自己的用例 .
第一步是为http客户端创建帮助程序类 .
然后,您可以在代码中使用此类 .
这是一个如何使用上面的类调用没有持有者的其余api的示例 .
这是一个如何调用需要持有者的其余api的例子 .
你还可以参考下面的repo,如果你想看到它的工作原理的工作实例 .
https://github.com/mokh223/callApi