วิธีนี้นี้ดี แต่ใช้ใน Web Services ไม่ได้ ถ้าจะเรียกใน Web Services ดู การเรียก POST ด้วย WebClient
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace Console2
{
class Product
{
public string username { get; set; }
public string password { get; set; }
public string TransactionId { get; set; }
public string Type { get; set; }
public string OutletCode { get; set; }
public string Class { get; set; }
public string Subclass { get; set; }
public string DocDate { get; set; }
}
class ResultProduct
{
public string ResultCode { get; set; }
public string ResultDesc { get; set; }
public string ApplicationNo { get; set; }
public string DocumentType { get; set; }
public string debitnote { get; set; }
public string dfbookno { get; set; }
public string dfcdno { get; set; }
}
class Program
{
static void Main(string[] args)
{
RunAsync().GetAwaiter().GetResult();
Console.WriteLine("---Main end---");
}
static async Task RunAsync()
{
string result = await MakePost();
Console.WriteLine("Result is " + result);
Console.WriteLine("---RunAsync end---");
}
static async Task<string> MakePost()
{
HttpClient client = new HttpClient();
Console.WriteLine("RunAsync");
Product product = new Product();
product.username = "myUser";
product.password = "myPassword";
string url = "http://www.example.com";
Console.WriteLine("RunAsync - url: " + url);
//var response = await client.PostAsync(url, content);
var response = await client.PostAsJsonAsync(url, product);
response.EnsureSuccessStatusCode();
//return response.Headers.Location;
var responseString = await response.Content.ReadAsStringAsync();
//Console.WriteLine(responseString);
ResultProduct result = JsonConvert.DeserializeObject<ResultProduct>(responseString);
Console.WriteLine("---Task end---");
return responseString;
}
}
}
บรรทัดที่ 14 : คลาส Product เป็นข้อมูลที่เอาไว้ส่ง
บรรทัดที่ 26 : คลาส ResultProduct ไว้รับข้อมูลกลับมา
บรรทัดที่ 63 : กำหนด url
บรรทัดที่ 59-61 : กำหนดค่า json ที่จะส่งไป
บรรทัดที่ 67 : กำหนดเมธอด POST แบบ json async