Hur gör jag anrop till ett REST-api med hjälp av C#?

Detta är den kod jag har hittills:

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

        }
    }
}

Problemet är att jag tror att undantagsblocket utlöses (för när jag tar bort try-catch får jag ett serverfelmeddelande (500). Men jag ser inte de Console.Out-rader som jag satte in i catch-blocket.

Min Console:


Tråden 'vshost.NotifyLoad' (0x1a20) har avslutats med kod 0 (0x0).
Tråden '<No Name>' (0x1988) har avslutats med kod 0 (0x0).
Tråden 'vshost.LoadReference' (0x1710) har avslutats med kod 0 (0x0).
'ConsoleApplication1.vshost.exe' (Hanterad (v4.0.30319)): Laddat 'c:\users\l. preston sego iii\documents\visual studio 11\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe', symboler laddade.
'ConsoleApplication1.vshost.exe' (Hanterad (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols. Modulen är optimerad och felsökningsalternativet 'Just My Code' är aktiverat.
Ett förstahandsundantag av typen 'System.Net.WebException' inträffade i System.dll
Tråden 'vshost.RunParkingWindow' (0x184c) har avslutats med kod 0 (0x0).
Tråden '<No Name>' (0x1810) har avslutats med kod 0 (0x0).
Programmet '[2780] ConsoleApplication1.vshost.exe: Program Trace' har avslutats med kod 0 (0x0).
Programmet '[2780] ConsoleApplication1.vshost.exe: Managed (v4.0.30319)' har avslutats med kod 0 (0x0).
```

Jag använder Visual Studio 2011 Beta och .NET 4.5 Beta.

Mitt förslag är att använda RestSharp. Du kan göra anrop till REST-tjänster och få dem omvandlade till POCO-objekt med mycket lite koder för att faktiskt analysera svaret. Detta löser inte ditt specifika fel, men svarar på din övergripande fråga om hur man gör anrop till REST-tjänster. Att behöva ändra koden för att använda den bör ge resultat i form av användarvänlighet och robusthet i framtiden. Detta är bara mina två cent.

Kommentarer (10)

Det har säkert inget med saken att göra, men omsluta dina IDisposable-objekt i using-block för att se till att du gör dig av med dem på rätt sätt:

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

        }
    }
}
Kommentarer (3)

Eftersom du använder Visual Studio 11 Beta vill du använda den senaste och bästa versionen. Det nya Web Api innehåller klasser för detta.

Se HttpClient: http://wcf.codeplex.com/wikipage?title=WCF%20HTTP

Kommentarer (0)