c# – 通过HttpClient向Paucelabs发送PUT请求没有响应
作者:互联网
我试图发送一个PUT请求通过their API更新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的功能时设置作业的名称.
解决方法:
Why does this request hang and what can I do to make it successful?
很可能是在客户端上混合了异步和阻塞调用,如.Result.SendAsync方法可能会导致死锁,或者当你放置它时,导致代码挂起.
考虑使用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();
}
}
标签:c,rest,net,selenium-webdriver,remotewebdriver 来源: https://codeday.me/bug/20190627/1307764.html