2017-04-04 294 views
4

我想通過their API發送PUT請求更新Saucelabs的作業。但是,下面的代碼掛起,我不知道爲什麼。通過HttpClient發送PUT請求到Saucelabs沒有響應

using (var client = new HttpClient()) 
{ 
    var sessionId = Browser.Driver.GetSessionId(); 
    var uri = new Uri($"https://saucelabs.com/rest/v1/{Configuration.SauceUserName}/jobs/{sessionId}"); 
    var uriWithCred = 
     new UriBuilder(uri) 
     { 
      UserName = $"{Configuration.SauceUserName}", 
      Password = $"{Configuration.SauceAccessKey}" 
     }.Uri; 
    var payload = new StringContent($"{{\"name\":\"{TestMethodName}\"}}", Encoding.UTF8, "application/json"); 
    var request = new HttpRequestMessage 
    { 
     Method = HttpMethod.Put, 
     RequestUri = uriWithCred, 
     Content = payload 
    }; 
    var response = client.SendAsync(request).Result;     
} 

以下cUrl請求成功(當然是編輯憑據)。

curl -X PUT -s -u <username>:<access-key> 
-d "{\"name\": \"test name\"}" 
https://saucelabs.com/rest/v1/<username>/jobs/<job-id> 

爲什麼這個請求掛起,我能做些什麼,使之成功?

由於與問題無關的原因,在設置WebDriver的功能時,我無法設置作業的名稱。

+0

假設它掛在等待響應,你用菲德勒(或任何其他工具)對你的代碼比較兩個請求的報頭(VS cUrl作者? – yonisha

回答

3

爲什麼這個請求掛起,我該怎麼做才能使它成功?

最有可能是在client.SendAsync方法異步和阻塞調用像.Result這可能會導致死鎖或者你把它,原因代碼掛的混合。

考慮使用await一直使該方法調用異步。

public async Task CallAPIAsync() {  
    using (var client = new HttpClient()) { 
     var sessionId = Browser.Driver.GetSessionId(); 
     var uri = new Uri($"https://saucelabs.com/rest/v1/{Configuration.SauceUserName}/jobs/{sessionId}"); 
     var uriWithCred = 
      new UriBuilder(uri) { 
       UserName = $"{Configuration.SauceUserName}", 
       Password = $"{Configuration.SauceAccessKey}" 
      }.Uri; 
     var payload = new StringContent($"{{\"name\":\"{TestMethodName}\"}}", Encoding.UTF8, "application/json"); 
     var request = new HttpRequestMessage { 
      Method = HttpMethod.Put, 
      RequestUri = uriWithCred, 
      Content = payload 
     }; 
     var response = await client.SendAsync(request); 

     var content = await response.Content.ReadAsStringAsync(); 
    } 
} 
+0

這爲我工作,謝謝!我不在.NET中有任何異步機制的實際經驗,你有任何鏈接或資源,你推薦? – Muttonchop

+1

@Muttonchop,這是我開始與async/await。作者是一個權威的主題。 msdn.microsoft.com/en-us/magazine/jj991977.aspx – Nkosi

相關問題