8

如何設置Timeout屬性爲HttpClient操作。我使用的代碼示例如下。如何在windows phone 8.1/Windows 8.1中設置http客戶端請求操作的超時時間

public HttpClient httpClient; 
public CancellationTokenSource cts; 

Public void SendRequest(addressUri,postrequestbody) 
{ 
    HttpHelper.CreateHttpClient(ref httpClient); 
    cts = new CancellationTokenSource(); 
    HttpRequestMessage msg = 
     new HttpRequestMessage(new HttpMethod("POST"), 
           new Uri(addressUri)); 
    msg.Content = new HttpStringContent(postrequestbody); 
    msg.Content.Headers.ContentType = 
     new HttpMediaTypeHeaderValue("application/json"); 
    HttpResponseMessage response = 
     await httpClient.SendRequestAsync(msg).AsTask(); 

    if (response.StatusCode == HttpStatusCode.Ok) 
    { 
    } 
} 

回答

8

使用CancellationToken

try 
{ 
    CancellationTokenSource cts = new CancellationTokenSource(2000); // 2 seconds 
    HttpClient client = new HttpClient(); 
    HttpResponseMessage response = await 
     client.SendRequestAsync(request).AsTask(cts.Token); 
} 
catch (TaskCanceledException ex) 
{ 
    // Catch operation aborted ... 
} 
+0

你試過超時>60秒? (您的示例使用2秒) 我試圖設置10分鐘像這樣..... var response = await httpClient.PutAsync(operation,payload,new CancellationTokenSource(600000).Token); 但是這仍然會在60秒後返回404 NOT FOUND。 – iupchris10 2015-09-10 15:22:41

+0

@ iupchris10我知道這就像2年太晚了,但60秒不到10分鐘。如果你有一個響應碼(即服務器有_responded_),那麼你的請求沒有超時。我會預期這種行爲,因爲這是正確的行爲。如果沒有響應/響應時間過長,上述代碼將在10分鐘後取消您的請求。在你的例子中情況並非如此。 – john 2017-10-11 06:35:35