ฉันมีเว็บ API ที่ฉันสามารถเข้าถึงได้ผ่านเบราว์เซอร์: -
ฉันกำลังพยายามสร้างโปรแกรมคอนโซลอย่างง่ายใน C# โดยใช้ VS2015 เพื่อส่งข้อมูลและรับการตอบกลับโดยใช้ http POST
นี่คือสิ่งที่ฉันมี: -
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace WebSample
{
class ApiSendData
{
public string UserID { get; set;} // username
public string Password { get; set;} // password for the webapi
public string ApiFunction { get; set; }
public string DppName { get; set; }
public string ClearData { get; set; }
public string DppVersion { get; set; }
}
class Program
{
static void Main(string[] args)
{
// The Main function calls an async method named RunAsync
// and then blocks until RunAsyncc completes.
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
//specify to use TLS 1.2 as default connection
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
// This code sets the base URI for HTTP requests,
// and sets the Accept header to "application/json",
// which tells the server to send data in JSON format.
client.BaseAddress = new Uri("https://localhost:8443/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var datatobeSent = new ApiSendData()
{
UserID = "xxxx",
Password = "yyyy",
ApiFunction ="NcrSecureData",
DppName ="CSampleCustomer",
DppVersion ="Latest",
ClearData ="1234567890",
ResultType = "JSON"
};
HttpResponseMessage response = await client.PostAsJsonAsync("ncrApi", datatobeSent);
if (response.IsSuccessStatusCode)
{
// Get the URI of the created resource.
Uri ncrUrl = response.Headers.Location;
// do whatever you need to do here with the returned data //
}
}
}
}
}
ในตัวแปรตอบกลับของฉัน ฉันได้รับข้อความ 200 OK http 1.1 โดยมี content type = application/json และ content-length = 174... แต่ไม่ได้รับข้อมูลจริง...
ตัวแปร ncrUrl ก็เป็นโมฆะเช่นกัน....
ฉันสงสัยว่าฉันต้องการคำสั่งเพิ่มเติมในโปรแกรมคอนโซลเพื่อรับข้อมูลหรือไม่
นี่คือสิ่งที่ฉันได้ติดตาม:- http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
string payload = await response.Content.ReadAsStringAsync();
- person Crowcoder   schedule 26.07.2016