-
Notifications
You must be signed in to change notification settings - Fork 114
/
HttpURLConnectionClient.cs
163 lines (140 loc) · 6.35 KB
/
HttpURLConnectionClient.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
using Adyen.EcommLibrary.Constants;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Adyen.EcommLibrary.HttpClient.Interfaces;
using Adyen.EcommLibrary.Model;
namespace Adyen.EcommLibrary.HttpClient
{
public class HttpUrlConnectionClient : IClient
{
private readonly Encoding _encoding = Encoding.ASCII;
public string Request(string endpoint, string json, Config config, bool isApiKeyRequired, RequestOptions requestOptions = null)
{
string responseText = null;
var httpWebRequest = GetHttpWebRequest(endpoint, config, isApiKeyRequired, requestOptions);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
using (var response = (HttpWebResponse)httpWebRequest.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream(), _encoding))
{
responseText = reader.ReadToEnd();
}
}
}
catch (WebException e)
{
var response = (HttpWebResponse)e.Response;
using (var sr = new StreamReader(response.GetResponseStream()))
{
responseText = sr.ReadToEnd();
}
throw new HttpClientException((int)response.StatusCode, "HTTP Exception", response.Headers, responseText);
}
return responseText;
}
/// <summary>
/// HttpWebRequest asynchronous.
/// </summary>
/// <param name="endpoint"></param>
/// <param name="json"></param>
/// <param name="config"></param>
/// <param name="isApiKeyRequired"></param>
/// <param name="requestOptions">Optional parameter used to specify the options for the request</param>
/// <returns>Task<string></returns>
public async Task<string> RequestAsync(string endpoint, string json, Config config, bool isApiKeyRequired, RequestOptions requestOptions = null)
{
string responseText;
//Set security protocol. Only TLS1.2
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = GetHttpWebRequest(endpoint, config, isApiKeyRequired, requestOptions);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
using (var response = (HttpWebResponse)await httpWebRequest.GetResponseAsync())
{
using (var reader = new StreamReader(response.GetResponseStream(), _encoding))
{
responseText = await reader.ReadToEndAsync();
}
}
return responseText;
}
[Obsolete("This is deprecated functionality by Adyen. Correct use request method with isApiKeyRequired parameter.")]
public string Request(string endpoint, string json, Config config)
{
return this.Request(endpoint, json, config, false);
}
public string Post(string endpoint, Dictionary<string, string> postParameters, Config config)
{
var dictToString = QueryString(postParameters);
byte[] postBytes = Encoding.ASCII.GetBytes(dictToString);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(endpoint);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.ContentLength = postBytes.Length;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (var stream = httpWebRequest.GetRequestStream())
{
stream.Write(postBytes, 0, postBytes.Length);
}
var response = (HttpWebResponse)httpWebRequest.GetResponse();
return new StreamReader(response.GetResponseStream()).ReadToEnd();
}
public HttpWebRequest GetHttpWebRequest(string endpoint, Config config, bool isApiKeyRequired, RequestOptions requestOptions = null)
{
//Add default headers
var httpWebRequest = (HttpWebRequest)WebRequest.Create(endpoint);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Accept-Charset", "UTF-8");
httpWebRequest.Headers.Add("Cache-Control", "no-cache");
httpWebRequest.UserAgent = $"{config.ApplicationName} {ClientConfig.UserAgentSuffix}{ClientConfig.LibVersion}";
if (config.SkipCertValidation)
{
httpWebRequest.ServerCertificateValidationCallback = delegate { return true; };
}
if (!string.IsNullOrWhiteSpace(requestOptions?.IdempotencyKey))
{
httpWebRequest.Headers.Add("Idempotency-Key", requestOptions?.IdempotencyKey);
}
//Use one of two authentication method.
if (isApiKeyRequired || !string.IsNullOrEmpty(config.XApiKey))
{
httpWebRequest.Headers.Add("x-api-key", config.XApiKey);
}
else if (!string.IsNullOrEmpty(config.Password))
{
var authString = config.Username + ":" + config.Password;
var bytes = Encoding.ASCII.GetBytes(authString);
var credentials = Convert.ToBase64String(bytes);
httpWebRequest.Headers.Add("Authorization", "Basic " + credentials);
httpWebRequest.UseDefaultCredentials = true;
}
return httpWebRequest;
}
public static string QueryString(IDictionary<string, string> dict)
{
var list = new List<string>();
foreach (var item in dict)
{
list.Add(item.Key + "=" + HttpUtility.UrlEncode(item.Value));
}
return string.Join("&", list);
}
}
}