-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathHttpClient.cs
78 lines (65 loc) · 2.26 KB
/
HttpClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace PayPalHttp
{
public class HttpClient
{
public Encoder Encoder { get; }
protected Environment environment;
private System.Net.Http.HttpClient client;
private List<IInjector> injectors;
public HttpClient(Environment environment)
{
this.environment = environment;
this.injectors = new List<IInjector>();
this.Encoder = new Encoder();
client = new System.Net.Http.HttpClient();
client.BaseAddress = new Uri(environment.BaseUrl());
client.DefaultRequestHeaders.Add("User-Agent", GetUserAgent());
}
protected virtual string GetUserAgent()
{
return "PayPalHttp-Dotnet HTTP/1.1";
}
public void AddInjector(IInjector injector)
{
if (injector != null)
{
this.injectors.Add(injector);
}
}
public void SetConnectTimeout(TimeSpan timeout)
{
client.Timeout = timeout;
}
public virtual async Task<HttpResponse> Execute<T>(T req) where T: HttpRequest
{
var request = req.Clone<T>();
foreach (var injector in injectors) {
injector.Inject(request);
}
request.RequestUri = new Uri(this.environment.BaseUrl() + request.Path);
if (request.Body != null)
{
request.Content = Encoder.SerializeRequest(request);
}
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
object responseBody = null;
if (response.Content.Headers.ContentType != null)
{
responseBody = Encoder.DeserializeResponse(response.Content, request.ResponseType);
}
return new HttpResponse(response.Headers, response.StatusCode, responseBody);
}
else
{
var responseBody = await response.Content.ReadAsStringAsync();
throw new HttpException(response.StatusCode, response.Headers, responseBody);
}
}
}
}