我有一个可以通过浏览器成功访问的web api: -
我正在尝试使用VS2015在C#中创建一个简单的控制台程序来发送数据并使用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消息,内容类型= application / json,content-length = 174 ...但是没有收到实际数据......
变量ncrUrl也是null ....
我想知道我的控制台程序中是否需要其他语句才能接收数据?
以下是我一直关注的事项: - http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
答案 0 :(得分:0)
在阅读评论后,您的api似乎被配置为返回文件而不是字符串内容(如JSON或XML)。您可以使用HttpContent.ReadAsStreamAsync Method读取响应流并将其保存到文件中。
HttpResponseMessage response = await client.PostAsJsonAsync("ncrApi", datatobeSent);
using (Stream output = File.OpenWrite("filename.txt")) // change
{
using (Stream input = await response.Content.ReadAsStreamAsync())
{
input.CopyTo(output);
}
}