2016-05-04 124 views
1

我想從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(); 

    } 
} 
+0

嘿,SOZ我錯過了聊天請求早些時候,聽起來像你到達那裏,我通常掛在c#聊天室,如果你需要在HTTP有這方面的更多幫助,流行://聊天.stackoverflow.com/rooms/7/c – War

回答

1

您的問題是...

var response = client.GetAsync(urlParameter); 

。 ..返回一個任務,你需要等待它完成第一個任務。

將此通話最清晰的方式是這樣的......

var response = await client.GetAsync(urlParameter); 

...這需要的代碼在這樣的異步方法運行...

public async Task Foo() 
{ 
    var response = await client.GetAsync(urlParameter); 
} 

。 ..或者你可以簡單地告訴編譯器等待...

var task = client.GetAsync(urlParameter); 
task.Wait(); 

var response = task.Result; 

...或更緊湊的版本可能會使用ac ontinuation像這樣...

var result = await client.GetAsync(urlParameter) 
    .ContinueWith(t => t.Result.Content.ReadAsAsync<IEnumerable<MyType>>()) 
    .Unwrap(); 

...這會做的請求,那麼當請求回來asyncronously解析它爲你展開任務返回「內的結果」,因爲這代碼創建一個任務>>而你只是想IEnumerable等待解包任務得到你的結果2個任務正在執行一個接一個:)

...我看着你的具體代碼,並在一個新的控制檯應用程序運行,請更新它對此...

class MyType 
     { 
      public int userId { get; set; } 
      public int id { get; set; } 
      public string title { get; set; } 
      public string body { get; set; } 
     } 

     static void TestAnApiCall() 
     { 
      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 readTask = response.Content.ReadAsAsync<MyType>(); 
        readTask.Wait(); 
        var dataObj = readTask.Result; 
        Console.WriteLine(JsonConvert.SerializeObject(dataObj)); 
       } 
      } 
      catch (Exception ex) 
      { 
       string a = ex.Message; 
       string b = ex.ToString(); 
      } 
     } 
+0

感謝您的解釋,但是我仍然得到相同的錯誤。在這種情況下,我去了task.Wait()路線,那是它產生相同錯誤的地方。我確實驗證了這個API,我可以在一個單獨的項目中通過ajax調用它。不過,我無法通過我的Windows服務進行此調用。 – PrivateJoker

+0

嗯...好吧,如果你可以更新你的問題中的代碼,也許用一個顯示任務正確使用的編輯,那麼新的異常的細節我應該能夠幫助你,但很難說,沒有看到實際的代碼你被困住了。我知道我的答案是有效的,因爲我一直都在做這種事情。 – War

+0

根據要求更新了代碼 – PrivateJoker