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

        }
    }
}

問題は、例外ブロックがトリガーされていると思われることです(try-catchを削除すると、サーバーエラー(500)のメッセージが表示されるからです。 しかし、catchブロックに入れたConsole.Outの行が表示されません。

私のConsole:

``none スレッド 'vshost.NotifyLoad' (0x1a20) はコード 0 (0x0) で終了しました。 スレッド '' (0x1988)がコード0(0x0)で終了しました。 スレッド 'vshost.LoadReference' (0x1710)がコード 0 (0x0)で終了しました。 'ConsoleApplication1.vshost.exe' (Managed (v4.0.30319)):Loaded 'c:users\l.preston sego iii\documents\visual studio 11\Projects\ConsoleApplication1ConsoleApplication1\binDebug\ConsoleApplication1.exe', Symbols loaded. 'ConsoleApplication1.vshost.exe' (Managed (v4.0.30319)):Loaded 'C:Japanese.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols.モジュールは最適化されており、デバッガのオプション 'Just My Code'が有効になっています。 System.dll で 'System.Net.WebException'タイプのファーストチャンス例外が発生しました。 スレッド 'vshost.RunParkingWindow' (0x184c)がコード 0 (0x0)で終了しました。 スレッド '' (0x1810)がコード0(0x0)で終了しました。 プログラム '[2780] ConsoleApplication1.vshost.exe:プログラムのトレース'はコード 0 (0x0)で終了しました。 プログラム '[2780] ConsoleApplication1.vshost.exe:Managed (v4.0.30319)' はコード 0 (0x0) で終了しました。



Visual Studio 2011 Beta、.NET 4.5 Betaを使用しています。

私が提案するのは、RestSharpを使うことです。RESTサービスへの呼び出しを行い、POCOオブジェクトにキャストすることができ、実際にレスポンスを解析するためのボイラープレートコードはほとんどありません。これは、あなたの特定のエラーを解決するものではありませんが、RESTサービスへの呼び出しをどのように行うかという全体的な質問に答えるものです。これを使用するためにコードを変更する必要がありますが、将来的には使いやすさと堅牢性の向上につながるはずです。これは私の2セントに過ぎませんが

解説 (10)

関係ないかもしれませんが、IDisposableオブジェクトをusingブロックで包んで、適切な処理ができるようにしてください。

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

        }
    }
}
解説 (3)

Visual Studio 11 Betaを使用しているので、最新かつ最高のものを使用したいと思います。新しいWeb Apiには、このためのクラスが含まれています。

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

解説 (0)