-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathHttpUtility.cs
More file actions
177 lines (151 loc) · 7.4 KB
/
HttpUtility.cs
File metadata and controls
177 lines (151 loc) · 7.4 KB
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
namespace AuthorizeNet.Util
{
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using AuthorizeNet.Api.Contracts.V1;
using AuthorizeNet.Api.Controllers.Bases;
#pragma warning disable 1591
public static class HttpUtility {
//Max response size allowed: 64 MB
private const int MaxResponseLength = 67108864;
private static readonly Log Logger = LogFactory.getLog(typeof(HttpUtility));
private static bool _proxySet;// = false;
static readonly bool UseProxy = AuthorizeNet.Environment.getBooleanProperty(Constants.HttpsUseProxy);
static readonly String ProxyHost = AuthorizeNet.Environment.GetProperty(Constants.HttpsProxyHost);
static readonly int ProxyPort = AuthorizeNet.Environment.getIntProperty(Constants.HttpsProxyPort);
private static Uri GetPostUrl(AuthorizeNet.Environment env)
{
var postUrl = new Uri(env.getXmlBaseUrl() + "/xml/v1/request.api");
Logger.debug(string.Format("Creating PostRequest Url: '{0}'", postUrl));
return postUrl;
}
public static ANetApiResponse PostData<TQ, TS>(AuthorizeNet.Environment env, TQ request, Guid requestId)
where TQ : ANetApiRequest
where TS : ANetApiResponse
{
ANetApiResponse response = null;
if (null == request)
{
throw new ArgumentNullException("request");
}
Logger.debug(string.Format("MerchantInfo->LoginId/TransactionKey: '{0}':'{1}'->{2}",
request.merchantAuthentication.name, request.merchantAuthentication.ItemElementName, request.merchantAuthentication.Item));
var postUrl = GetPostUrl(env);
var webRequest = (HttpWebRequest) WebRequest.Create(postUrl);
webRequest.Method = "POST";
webRequest.ContentType = "text/xml";
webRequest.KeepAlive = true;
webRequest.Proxy = SetProxyIfRequested(webRequest.Proxy);
//add corelationId
webRequest.Headers[Constants.DCDRequestIdHeaderName] = requestId.ToString();
Logger.info( string.Format("Co-relationId for the web-request: {0} ", requestId));
//set the http connection timeout
var httpConnectionTimeout = AuthorizeNet.Environment.getIntProperty(Constants.HttpConnectionTimeout);
webRequest.Timeout = (httpConnectionTimeout != 0 ? httpConnectionTimeout : Constants.HttpConnectionDefaultTimeout);
//set the time out to read/write from stream
var httpReadWriteTimeout = AuthorizeNet.Environment.getIntProperty(Constants.HttpReadWriteTimeout);
webRequest.ReadWriteTimeout = (httpReadWriteTimeout != 0 ? httpReadWriteTimeout : Constants.HttpReadWriteDefaultTimeout);
var requestType = typeof (TQ);
var serializer = new XmlSerializer(requestType);
using (var writer = new XmlTextWriter(webRequest.GetRequestStream(), Encoding.UTF8))
{
serializer.Serialize(writer, request);
}
// Get the response
String responseAsString = null;
Logger.debug(string.Format("Retreiving Response from Url: '{0}'", postUrl));
// Set Tls to Tls1.2
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
using (var webResponse = webRequest.GetResponse())
{
Logger.debug(string.Format("Received Response: '{0}'", webResponse));
using (var responseStream = webResponse.GetResponseStream())
{
if (null != responseStream)
{
var result = new StringBuilder();
using (var reader = new StreamReader(responseStream))
{
while (!reader.EndOfStream)
{
result.Append((char)reader.Read());
if (result.Length >= MaxResponseLength)
{
throw new Exception("response is too long.");
}
}
responseAsString = result.Length > 0 ? result.ToString() : null;
}
Logger.debug(string.Format("Response from Stream: '{0}'", responseAsString));
}
}
}
if (null != responseAsString)
{
using (var memoryStreamForResponseAsString = new MemoryStream(Encoding.UTF8.GetBytes(responseAsString)))
{
var responseType = typeof (TS);
var deSerializer = new XmlSerializer(responseType);
Object deSerializedObject;
try
{
// try deserializing to the expected response type
deSerializedObject = deSerializer.Deserialize(memoryStreamForResponseAsString);
}
catch (Exception)
{
// probably a bad response, try if this is an error response
memoryStreamForResponseAsString.Seek(0, SeekOrigin.Begin); //start from beginning of stream
var genericDeserializer = new XmlSerializer(typeof (ANetApiResponse));
deSerializedObject = genericDeserializer.Deserialize(memoryStreamForResponseAsString);
}
//if error response
if (deSerializedObject is ErrorResponse)
{
response = deSerializedObject as ErrorResponse;
}
else
{
//actual response of type expected
if (deSerializedObject is TS)
{
response = deSerializedObject as TS;
}
else if (deSerializedObject is ANetApiResponse) //generic response
{
response = deSerializedObject as ANetApiResponse;
}
}
}
}
return response;
}
public static IWebProxy SetProxyIfRequested(IWebProxy proxy)
{
var newProxy = proxy as WebProxy;
if (UseProxy)
{
var proxyUri = new Uri(string.Format("{0}://{1}:{2}", Constants.ProxyProtocol, ProxyHost, ProxyPort));
if (!_proxySet)
{
Logger.info(string.Format("Setting up proxy to URL: '{0}'", proxyUri));
_proxySet = true;
}
if (null == proxy || null == newProxy)
{
newProxy = new WebProxy(proxyUri);
}
newProxy.UseDefaultCredentials = true;
newProxy.BypassProxyOnLocal = true;
}
return (newProxy ?? proxy);
}
}
#pragma warning restore 1591
}
//http://ecommerce.shopify.com/c/shopify-apis-and-technology/t/c-webrequest-put-and-xml-49458
//http://www.808.dk/?code-csharp-httpwebrequest