example request c# HTTP POST Webリクエストを作成する方法




5 Answers

シンプルなGETリクエスト

using System.Net;

...

using (var wb = new WebClient())
{
    var response = wb.DownloadString(url);
}

シンプルなPOSTリクエスト

using System.Net;
using System.Collections.Specialized;

...

using (var wb = new WebClient())
{
    var data = new NameValueCollection();
    data["username"] = "myUser";
    data["password"] = "myPassword";

    var response = wb.UploadValues(url, "POST", data);
    string responseInString = Encoding.UTF8.GetString(response);
}
c# webrequest post file

HTTPリクエストを作成し、 POSTメソッドを使用してデータを送信するにはどうすればよいですか? 私はGET要求をすることができますが、 POSTどうやって作るのか分かりません。




これはJSON形式でデータを送受信する完全な実例です。私はVS2013 Express Edition

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace ConsoleApplication1
{
    class Customer
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
    }

    public class Program
    {
        private static readonly HttpClient _Client = new HttpClient();
        private static JavaScriptSerializer _Serializer = new JavaScriptSerializer();

        static void Main(string[] args)
        {
            Run().Wait();
        }

        static async Task Run()
        {
            string url = "http://www.example.com/api/Customer";
            Customer cust = new Customer() { Name = "Example Customer", Address = "Some example address", Phone = "Some phone number" };
            var json = _Serializer.Serialize(cust);
            var response = await Request(HttpMethod.Post, url, json, new Dictionary<string, string>());
            string responseText = await response.Content.ReadAsStringAsync();

            List<YourCustomClassModel> serializedResult = _Serializer.Deserialize<List<YourCustomClassModel>>(responseText);

            Console.WriteLine(responseText);
            Console.ReadLine();
        }

        /// <summary>
        /// Makes an async HTTP Request
        /// </summary>
        /// <param name="pMethod">Those methods you know: GET, POST, HEAD, etc...</param>
        /// <param name="pUrl">Very predictable...</param>
        /// <param name="pJsonContent">String data to POST on the server</param>
        /// <param name="pHeaders">If you use some kind of Authorization you should use this</param>
        /// <returns></returns>
        static async Task<HttpResponseMessage> Request(HttpMethod pMethod, string pUrl, string pJsonContent, Dictionary<string, string> pHeaders)
        {
            var httpRequestMessage = new HttpRequestMessage();
            httpRequestMessage.Method = pMethod;
            httpRequestMessage.RequestUri = new Uri(pUrl);
            foreach (var head in pHeaders)
            {
                httpRequestMessage.Headers.Add(head.Key, head.Value);
            }
            switch (pMethod.Method)
            {
                case "POST":
                    HttpContent httpContent = new StringContent(pJsonContent, Encoding.UTF8, "application/json");
                    httpRequestMessage.Content = httpContent;
                    break;

            }

            return await _Client.SendAsync(httpRequestMessage);
        }
    }
}



私が今までに見つけたシンプルな(1ライナー、エラーチェックなし、レスポンス待ち)解決策

(new WebClient()).UploadStringAsync(new Uri(Address), dataString);‏

慎重に使用してください!




IEnterprise.Easy-HTTPは、クラスの解析とクエリのビルドを組み込んでいるため、使用できます。

await new RequestBuilder<ExampleObject>()
.SetHost("https://httpbin.org")
.SetContentType(ContentType.Application_Json)
.SetType(RequestType.Post)
.SetModelToSerialize(dto)
.Build()
.Execute();

私は図書館の著者ですので、 github質問をしたりコードをチェックしたりしてください




流暢なAPIが好きなら、 Tiny.RestClientを使うことができますTiny.RestClientこれはTiny.RestClientで利用できます

var client = new TinyRestClient(new HttpClient(), "http://MyAPI.com/api");
// POST
 var city = new City() { Name = "Paris" , Country = "France"};
// With content
var response = await client.PostRequest("City", city).
                ExecuteAsync<bool>();

希望が助けてくれる!




Related