我已成功创建了一个托管在我的服务器上的PHP REST API。现在我想通过我的WPF C#应用程序创建客户端连接。我找到了这个,但我的API需要通过HTTP标头发送API密钥,并且我看不到这个方案可以实现。我还使用CURL创建了一个PHP REST客户端,非常容易使用,并希望C#内置有处理对REST服务的请求的东西。
如果有人能指向他们看过的教程或库,我将不胜感激。
谢谢。
如果有人能指向他们看过的教程或库,我将不胜感激。
谢谢。
看看RESTSharp吧。非常强大且易于使用。
适用于所有平台:Web、Windows、WCF、Monotouch、Windows Phone。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://a/rest/uri");
request.Method = "POST";
request.Headers.Add("Authorization: OAuth " + accessToken);
string postData = string.Format("param1=something¶m2=something_else");
byte[] data = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "application/json";
request.ContentLength = data.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
}
try
{
using(WebResponse response = request.GetResponse())
{
// Do something with response
}
}
catch (WebException ex)
{
// Handle error
}
同时,您可以在.NET 4.5中使用HttpClient。如果您正在使用.NET 4.0,则可以在Microsoft.Net.Http nuget中获取HttpClient
API。