如何使用c#调用REST api?
这是迄今为止的代码:
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); } } } }
问题是,我认为exception块正在被触发(因为当我删除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。
ASP.Net Web API已经取代了前面提到的WCF Web API。
我想我会发布一个更新的答案,因为这些答复大部分是从2012年初,这个线程是做一个谷歌search“呼叫平安服务C#”的最重要的结果之一。
微软当前的指导是使用Microsoft ASP.NET Web API客户端库来使用RESTful服务。 这是作为一个NuGet包,Microsoft.AspNet.WebApi.Client。
下面是您的示例在使用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! if (response.IsSuccessStatusCode) { // Parse the response body. Blocking! var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result; foreach (var d in dataObjects) { Console.WriteLine("{0}", d.Name); } } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } } } }
有关更多详细信息,请参阅其他示例: http:
这个博客文章也许是有用的: http : //johnnycode.com/2012/02/23/consuming-your-own-asp-net-web-api-rest-service/
我的build议是使用RestSharp 。 您可以调用REST服务,并使用很less的样板代码将它们投射到POCO对象中,以实际parsing响应。 这不会解决您的特定错误,但会回答您如何拨打REST服务的整体问题。 不得不改变你的代码来使用它,应该在易用性和健壮性方面前进。 这只是我的2美分
无关的,我敢肯定,但是要using
块来包装你的IDisposable
对象,以确保正确的处置:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System; 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; 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()) { if (webStream != 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); } } } }
使用.NET 4.5时调用REST API的更新。
我会build议DalSoft.RestClient (注意我创build它)。 原因是因为它使用dynamictypes,所以你可以把所有东西都包装在一个stream畅的调用中,包括序列化/反序列化。 下面是一个工作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 API请求使用下面的代码
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Json; namespace ConsoleApplication2 { class Program { private const string URL = "https://XXXX/rest/api/2/component"; private const string DATA = @"{ ""name"": ""Component 2"", ""description"": ""This is a JIRA component"", ""leadUserName"": ""xx"", ""assigneeType"": ""PROJECT_LEAD"", ""isAssigneeTypeValid"": false, ""project"": ""TP""}"; static void Main(string[] args) { AddComponent(); } private static void AddComponent() { System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); client.BaseAddress = new System.Uri(URL); byte[] cred = UTF8Encoding.UTF8.GetBytes("username:password"); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred)); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); System.Net.Http.HttpContent content = new StringContent(DATA, UTF8Encoding.UTF8, "application/json"); HttpResponseMessage messge = client.PostAsync(URL, content).Result; string description = string.Empty; if (messge.IsSuccessStatusCode) { string result = messge.Content.ReadAsStringAsync().Result; description = result; } } } }
var TakingRequset = WebRequest.Create("http://xxx.acv.com/MethodName/Get"); TakingRequset.Method = "POST"; TakingRequset.ContentType = "text/xml;charset=utf-8"; TakingRequset.PreAuthenticate = true; //---Serving Request path query var PAQ = TakingRequset.RequestUri.PathAndQuery; //---creating your xml as per the host reqirement string xmlroot=@"<root><childnodes>passing parameters</childnodes></root>"; string xmlroot2=@"<root><childnodes>passing parameters</childnodes></root>"; //---Adding Headers as requested by host xmlroot2 = (xmlroot2 + "XXX---"); //---Adding Headers Value as requested by host // var RequestheaderVales = Method(xmlroot2); WebProxy proxy = new WebProxy("XXXXX-----llll", 8080); proxy.Credentials = new NetworkCredential("XXX---uuuu", "XXX----", "XXXX----"); System.Net.WebRequest.DefaultWebProxy = proxy; // Adding The Request into Headers TakingRequset.Headers.Add("xxx", "Any Request Variable "); TakingRequset.Headers.Add("xxx", "Any Request Variable"); byte[] byteData = Encoding.UTF8.GetBytes(xmlroot); TakingRequset.ContentLength = byteData.Length; using (Stream postStream = TakingRequset.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); postStream.Close(); } StreamReader stredr = new StreamReader(TakingRequset.GetResponse().GetResponseStream()); string response = stredr.ReadToEnd();
由于您使用的是Visual Studio 11 Beta,因此您将需要使用最新,最好的。 新的Web Api包含这个类。
请参阅HttpClient: http ://wcf.codeplex.com/wikipage?title = WCF%20HTTP
检查重新打电话来从.netrest服务。 我发现它很容易使用: https : //github.com/paulcbetts/refit
改装:用于.NET Core,Xamarin和.NET的自动types安全的REST库
Refit是一个深受Square改造库启发的图书馆,它将您的REST API变成一个实时界面:
public interface IGitHubApi { [Get("/users/{user}")] Task<User> GetUser(string user); } The RestService class generates an implementation of IGitHubApi that uses HttpClient to make its calls: var gitHubApi = RestService.For<IGitHubApi>("https://api.github.com"); var octocat = await gitHubApi.GetUser("octocat");
这是一个确实有效的示例代码。 我花了一天的时间来阅读Rest服务的一组对象:
RootObject是从其他服务读取的对象的types。
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();
您可以尝试使用更简单的WebClient
类:
得到:
// GET JSON Response public WeatherResponseModel GET(string url) { WeatherResponseModel model = new WeatherResponseModel(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); try { WebResponse response = request.GetResponse(); using(Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); model = JsonConvert.DeserializeObject < WeatherResponseModel > (reader.ReadToEnd()); } } catch (WebException ex) { WebResponse errorResponse = ex.Response; using(Stream responseStream = errorResponse.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); String errorText = reader.ReadToEnd(); // log errorText } throw; } return model; }
POST:
// POST a JSON string void POST(string url, string jsonContent) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); Byte[]byteArray = encoding.GetBytes(jsonContent); request.ContentLength = byteArray.Length; request.ContentType = @ "application/json"; using(Stream dataStream = request.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); } long length = 0; try { using(HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { // got response length = response.ContentLength; } } catch (WebException ex) { WebResponse errorResponse = ex.Response; using(Stream responseStream = errorResponse.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); String errorText = reader.ReadToEnd(); // log errorText } throw; } }
注:要序列化和desirialze JSON我使用了Newtonsoft.Json NuGet包。