web-dev-qa-db-ja.com

C#を使用してPOSTリクエストでJSONデータを送信する方法

C#を使用してPOSTリクエストでJSONデータを送信したい。

私はいくつかの方法を試しましたが、多くの問題に直面しています。文字列からの生のjsonおよびjsonファイルからのjsonデータとして要求本文を使用して要求する必要があります。

これら2つのデータフォームを使用してリクエストを送信するにはどうすればよいですか。

例:jsonの認証要求本文の場合-> {"Username":"myusername","Password":"pass"}

他のAPIの場合、リクエストボディは外部jsonファイルから取得する必要があります。

17
Rocky

HttpClientおよびWebClientの代わりに HttpWebRequest を使用できます。それはより新しい実装です。

string myJson = "{'Username': 'myusername','Password':'pass'}";
using (var client = new HttpClient())
{
    var response = await client.PostAsync(
        "http://yourUrl", 
         new StringContent(myJson, Encoding.UTF8, "application/json"));
}

enter image description here

HttpClientが必要な場合は、インスタンスを1つだけ作成して再利用するか、新しいHttpClientFactoryを使用することをお勧めします。

38
NtFreX

HttpWebRequestでできます:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
            {
                Username = "myusername",
                Password = "pass"
            });
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}
15
kkakkurt

HttpClientまたはRestSharpのいずれかを使用できます。ここにあるurコードはhttpclientを使用した例ですのでわかりません。

using (var client = new HttpClient())
        {
            //This would be the like http://www.uber.com
            client.BaseAddress = new Uri("Base Address/URL Address");
            //serialize your json using newtonsoft json serializer then add it to the StringContent
            var content = new StringContent(YourJson, Encoding.UTF8, "application/json") 
            //method address would be like api/callUber:SomePort for example
            var result = await client.PostAsync("Method Address", content);
            string resultContent = await result.Content.ReadAsStringAsync();

        }
4
Valkyrie

これは私のために動作します。

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new 

StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
                {
                    Username = "myusername",
                    Password = "password"
                });

    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}
2
Rohan Das