我想从Windows服务调用Rest API。我从来没有尝试过。我不知道为什么我不能打这个电话。如何从Windows服务调用REST API
我的代码:
string urlParameter = "posts/1";
var client = new HttpClient();
client.BaseAddress = new Uri("http://jsonplaceholder.typicode.com/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(urlParameter).Result;
if (response.IsSuccessStatusCode)
{
var dataObj = response.Content.ReadAsAsync<IEnumerable<MyType>>().Result;
}
我收到以下错误:
消息:发送请求时发生错误。
内部异常消息:{ “基础连接已关闭:该 连接被意外关闭”}
内部异常堆栈跟踪在 System.Net.HttpWebRequest.EndGetResponse(IAsyncResult的asyncResult)
在System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult的 AR)
被上下面的行生成此错误:
HttpResponseMessage response = client.GetAsync(urlParameter).Result;
任何意见,将不胜感激。
编辑:(更新后的代码)
string urlParameter = "posts/1";
var client = new HttpClient();
client.BaseAddress = new Uri("http://jsonplaceholder.typicode.com/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
//var response = await client.GetAsync(urlParameter);
var task = client.GetAsync(urlParameter);
task.Wait();
var response = task.Result;
if (response.IsSuccessStatusCode)
{
var dataObj = response.Content.ReadAsAsync<IEnumerable<MyType>>().Result;
}
}
catch (Exception ex)
{
string a = ex.Message;
string b = ex.ToString();
}
编辑2:这里(仍然得到同样的错误)
private static async void TestAPI2()
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Get", "application/json");
var response = await client.GetAsync("http://jsonplaceholder.typicode.com/posts/1");
string context = await response.Content.ReadAsStringAsync();
}
}
嘿,SOZ我错过了聊天请求早些时候,听起来像你到达那里,我通常挂在c#聊天室,如果你需要在HTTP有这方面的更多帮助,流行://聊天.stackoverflow.com/rooms/7/c – War