Extract response exceptions
[smsapi-csharp.git] / smsapi / ProxyHTTP.cs
blobb09decf12b847229d272f26f52fde7596d14d7c2
1 using System;
2 using System.Collections.Generic;
3 using System.Collections.Specialized;
4 using System.IO;
5 using System.Net;
6 using System.Net.Http;
7 using System.Threading;
8 using System.Threading.Tasks;
10 namespace SMSApi.Api
12 public class ProxyHTTP : Proxy
14 private readonly string baseUrl;
15 private IClient authentication;
17 public ProxyHTTP(string baseUrl)
19 this.baseUrl = baseUrl;
22 public void Authentication(IClient client)
24 authentication = client;
27 public HttpResponseEntity Execute(string uri, NameValueCollection data, RequestMethod method)
29 return Execute(uri, data, new Dictionary<string, Stream>(), method);
32 public HttpResponseEntity Execute(
33 string uri,
34 NameValueCollection data,
35 Stream file,
36 RequestMethod method)
38 return Execute(uri, data, new Dictionary<string, Stream> { { "file", file } }, method);
41 public HttpResponseEntity Execute(
42 string uri,
43 NameValueCollection data,
44 Dictionary<string, Stream> files,
45 RequestMethod method)
47 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
49 HttpClient client = CreateClient();
51 try
53 return client.SendRequest(method, uri, data, files).Result;
55 catch (System.Exception e)
57 throw new ProxyException("Failed to get response from " + uri, e);
61 public async Task<HttpResponseEntity> ExecuteAsync(
62 string uri,
63 NameValueCollection data,
64 RequestMethod method,
65 CancellationToken cancellationToken = default
68 return await ExecuteAsync(uri, data, new Dictionary<string, Stream>(), method);
71 public async Task<HttpResponseEntity> ExecuteAsync(
72 string uri,
73 NameValueCollection data,
74 Stream file,
75 RequestMethod method,
76 CancellationToken cancellationToken = default
79 return await ExecuteAsync(uri, data, new Dictionary<string, Stream> { { "file", file } }, method);
82 public async Task<HttpResponseEntity> ExecuteAsync(
83 string uri,
84 NameValueCollection data,
85 Dictionary<string, Stream> files,
86 RequestMethod method,
87 CancellationToken cancellationToken = default
90 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
92 HttpClient client = CreateClient();
94 try
96 return await client.SendRequest(method, uri, data, files, cancellationToken);
98 catch (System.Exception e)
100 throw new ProxyException("Failed to get response from " + uri, e);
104 private HttpClient CreateClient()
106 var client = new HttpClient();
107 client.BaseAddress = new Uri(baseUrl);
108 client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", authentication.GetClientAgent());
110 if (authentication == null) return client;
112 var authHeader = authentication.DefaultRequestHeaders;
114 client.DefaultRequestHeaders.Add(authHeader.Key, authHeader.Value);
116 return client;