- การเรียก POST แบบส่ง key-value
- การเรียก POST แบบส่ง json
วิธีนี้ Legacy แล้ว แต่สะดวกตรงที่ไม่ใช้ async–await ทำให้ใช้ใน Web Services ได้
1.การเรียก POST แบบส่ง key-value
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Console3
{
class Program
{
static void Main(string[] args)
{
string url = "http://www.example.com";
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["username"] = "myUser";
data["password"] = "myPassword";
var response = wb.UploadValues(url, "POST", data);
string responseString = Encoding.UTF8.GetString(response);
}
}
}
}
บรรทัดที่ 15 : กำหนด url
บรรทัดที่ 19-21 : กำหนด key-value ที่จะส่งไป
บรรทัดที่ 23 : กำหนดเมธอด POST
บรรทัดที่ 24 : string ที่ส่งกลับมา
2.การเรียก POST แบบส่ง json
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Console3
{
class Program
{
static void Main(string[] args)
{
string url = "http://www.example.com";
using (var wb = new WebClient())
{
var json = "{\"username\": \"myUser\", ";
json += " \"password\": \"myPassword\"}";
wb.Headers[HttpRequestHeader.ContentType] = "application/json";
var response = wb.UploadString(url, "POST", json);
Console.WriteLine(response.ToString());
}
}
}
}
บรรทัดที่ 15 : กำหนด url
บรรทัดที่ 19-20 : กำหนดค่า json ที่จะส่งไป
บรรทัดที่ 22 : กำหนดเมธอด POST