今回の記事はHttpclientのPostAsyncでサーバにJsonデータをPost通信する方法に関しての記事です。初心者にも分かりやすいように記載していくので是非参考にしてみてください。
また、C#のPost通信の送信時の情報として、ヘッダーを追加する方法に関しても記載しているので興味のある方は下記記事も確認してみてください。
「【C#】HttpclientのPostAsyncにヘッダー追加を行いPost通信する方法ご紹介。」
HttpclientのPostAsyncでPost通信
Post通信は簡単です。下記コードで実装できます。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Test
{
// httpクライアント
private static HttpClient client = new HttpClient();
//レコード作成
static async Task Post()
{
//Post先URL
string url = "指定のURL";
//Post通信
HttpResponseMessage Response;
try
{
Response = await client.PostAsync(url);
}
catch
{
return;
}
}
}
詳しくは下記記事で紹介しているのでそちらをご確認ください。
「【C#】C#でhttp通信を行う方法。〜 Post通信・Get通信 〜」
ではJsonデータの送り方を確認していきます。
PostAsyncでJsonデータを送信
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Test
{
// httpクライアント
private static HttpClient client = new HttpClient();
//レコード作成
static async Task Post()
{
//Post先URL
string url = "指定のURL";
//Jsonデータ
string parameters = "{" +
" \"テスト\" : \"test\" ," +
" \"Json\" : \"ジェイソン\" ," +
" \"キー\" : \"バリュー\" }";
//Postで付与するパラメータ
var content = new StringContent(parameters, Encoding.UTF8, "application/json");
//リクエストヘッダーにアクセストークン付与
//client.DefaultRequestHeaders.Add("Authorization", "Bearer " + "アクセストークン");
//Post通信
HttpResponseMessage Response;
try
{
Response = await client.PostAsync(url, content);
}
catch
{
return;
}
}
}
}
少し解説を行います。文字列で記載したJsonデータをエンコードさせてjson形式に変換します。そのオブジェクトをPostAsyncの第2引数で一緒に送っているという感じです。
ではこんな気の記事は以上です。
コメント