【发布时间】:2016-07-25 16:14:14
【问题描述】:
我有一个可以通过浏览器成功访问的 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 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())
{
// 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/ncrApi");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var datatobeSent = new ApiSendData()
{
ApiFunction ="NcrSecureData",
DppName ="CSampleCustomer",
DppVersion ="Latest",
ClearData ="1234567890"
};
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 //
}
}
}
}
}
但是,我在 HttpResonseMessage 响应语句中遇到错误......{“发送请求时发生错误。”} {“请求中止:无法创建 SSL/TLS 安全通道。”}
我怀疑这是因为我没有正确理解 client.BaseAddress 和 HttpResponseMessage 响应语句。
这是我一直在关注的:- http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
【问题讨论】:
-
其他 cmets:- 1) 我关闭了 SSL 并成功连接到端口 8080 上的 web api。2) 我用我的代码成功连接到其他 SSL api。似乎 C# 代码在 SSL 连接上没有连接到 ncrApi。任何想法为什么?
标签: c# api post console http-post