22
33namespace LessAnnoyingHttp ;
44
5- public class Http {
5+ public static class Http {
6+ /// <summary>
7+ /// The timeout in seconds which requests should wait for before failing (default: 10)<br/>
8+ /// Changing this value changes the timeouts globally
9+ /// </summary>
10+ public static int Timeout { get ; set ; } = 10 ;
11+
612 /// <summary>
713 /// Sends a GET request
814 /// </summary>
@@ -11,6 +17,7 @@ public class Http {
1117 /// <returns><see cref="Response"/></returns>
1218 public static Response Get ( string endpoint , Header [ ] ? headers = null ) {
1319 using HttpClient client = new ( ) ;
20+ client . Timeout = TimeSpan . FromSeconds ( Timeout ) ;
1421 HttpRequestMessage request = new ( ) {
1522 RequestUri = new Uri ( endpoint ) ,
1623 Method = HttpMethod . Get
@@ -22,16 +29,19 @@ public static Response Get(string endpoint, Header[]? headers = null) {
2229
2330 HttpResponseMessage response ;
2431 try {
25- response = client . SendAsync ( request ) . Result ;
32+ response = client . Send ( request ) ;
33+ } catch ( TaskCanceledException ) {
34+ throw new TimeoutException ( $ "Timeout waiting for response for request to { endpoint } ") ;
2635 } catch ( Exception e ) {
27- return new Response { IsSuccessful = false , Body = "" , Exception = e } ;
36+ return new Response { IsSuccessful = false , Body = "" , Exception = e } ;
2837 }
2938
3039 return new Response { IsSuccessful = response . IsSuccessStatusCode , Body = response . Content . ReadAsStringAsync ( ) . Result , StatusCode = response . StatusCode } ;
3140 }
3241
3342 private static Response BodyRequest ( string endpoint , HttpMethod method , string body , Header [ ] ? headers , string contentType ) {
3443 using HttpClient client = new ( ) ;
44+ client . Timeout = TimeSpan . FromSeconds ( Timeout ) ;
3545 HttpRequestMessage request = new ( ) {
3646 RequestUri = new Uri ( endpoint ) ,
3747 Method = method ,
@@ -45,6 +55,8 @@ private static Response BodyRequest(string endpoint, HttpMethod method, string b
4555 HttpResponseMessage response ;
4656 try {
4757 response = client . Send ( request ) ;
58+ } catch ( TaskCanceledException ) {
59+ throw new TimeoutException ( $ "Timeout waiting for response for request to { endpoint } ") ;
4860 } catch ( Exception e ) {
4961 return new Response { IsSuccessful = false , Body = "" , Exception = e } ;
5062 }
0 commit comments