通过HttpClient发送PUT请求到Saucelabs没有响应

时间:2017-04-04 15:44:44

标签: c# .net rest selenium-webdriver remotewebdriver

我正在尝试通过Saucelabs发送PUT请求以更新their API上的职位。但是,以下代码挂起,我不确定原因。

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的功能时设置作业名称。

1 个答案:

答案 0 :(得分:3)

Why does this request hang and what can I do to make it successful?

Most probably there is a mixing of async and blocking calls like .Result on the client.SendAsync method which can cause deadlocks or as you put it, cause code to hang.

Consider making the method call async all the way using 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();
    }
}