-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
RestRequest.cs
669 lines (587 loc) · 26.6 KB
/
RestRequest.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
#region License
// Copyright 2010 John Sheehan
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using RestSharp.Serializers;
#if FRAMEWORK
using RestSharp.Extensions;
#endif
namespace RestSharp
{
/// <summary>
/// Container for data used to make requests
/// </summary>
public class RestRequest : IRestRequest
{
/// <summary>
/// Always send a multipart/form-data request - even when no Files are present.
/// </summary>
public bool AlwaysMultipartFormData { get; set; }
/// <summary>
/// Serializer to use when writing JSON request bodies. Used if RequestFormat is Json.
/// By default the included JsonSerializer is used (currently using JSON.NET default serialization).
/// </summary>
public ISerializer JsonSerializer { get; set; }
/// <summary>
/// Serializer to use when writing XML request bodies. Used if RequestFormat is Xml.
/// By default the included XmlSerializer is used.
/// </summary>
public ISerializer XmlSerializer { get; set; }
/// <summary>
/// Set this to write response to Stream rather than reading into memory.
/// </summary>
public Action<Stream> ResponseWriter { get; set; }
/// <summary>
/// Determine whether or not the "default credentials" (e.g. the user account under which the current process is running)
/// will be sent along to the server. The default is false.
/// </summary>
public bool UseDefaultCredentials { get; set; }
/// <summary>
/// Default constructor
/// </summary>
public RestRequest()
{
this.RequestFormat = DataFormat.Xml;
this.Method = Method.GET;
this.Parameters = new List<Parameter>();
this.Files = new List<FileParameter>();
this.XmlSerializer = new XmlSerializer();
this.JsonSerializer = new JsonSerializer();
this.OnBeforeDeserialization = r => { };
}
/// <summary>
/// Sets Method property to value of method
/// </summary>
/// <param name="method">Method to use for this request</param>
public RestRequest(Method method) : this()
{
this.Method = method;
}
/// <summary>
/// Sets Resource property
/// </summary>
/// <param name="resource">Resource to use for this request</param>
public RestRequest(string resource) : this(resource, Method.GET) { }
/// <summary>
/// Sets Resource and Method properties
/// </summary>
/// <param name="resource">Resource to use for this request</param>
/// <param name="method">Method to use for this request</param>
public RestRequest(string resource, Method method) : this()
{
this.Resource = resource;
this.Method = method;
}
/// <summary>
/// Sets Resource property
/// </summary>
/// <param name="resource">Resource to use for this request</param>
public RestRequest(Uri resource) : this(resource, Method.GET) { }
/// <summary>
/// Sets Resource and Method properties
/// </summary>
/// <param name="resource">Resource to use for this request</param>
/// <param name="method">Method to use for this request</param>
public RestRequest(Uri resource, Method method)
: this(resource.IsAbsoluteUri
? resource.AbsolutePath + resource.Query
: resource.OriginalString, method)
{
//resource.PathAndQuery not supported by Silverlight :(
}
/// <summary>
/// Adds a file to the Files collection to be included with a POST or PUT request
/// (other methods do not support file uploads).
/// </summary>
/// <param name="name">The parameter name to use in the request</param>
/// <param name="path">Full path to file to upload</param>
/// <param name="contentType">The MIME type of the file to upload</param>
/// <returns>This request</returns>
public IRestRequest AddFile(string name, string path, string contentType = null)
{
FileInfo f = new FileInfo(path);
long fileLength = f.Length;
return this.AddFile(new FileParameter
{
Name = name,
FileName = Path.GetFileName(path),
ContentLength = fileLength,
Writer = s =>
{
using (StreamReader file = new StreamReader( new FileStream(path, FileMode.Open)))
{
file.BaseStream.CopyTo(s);
}
},
ContentType = contentType
});
}
/// <summary>
/// Adds the bytes to the Files collection with the specified file name
/// </summary>
/// <param name="name">The parameter name to use in the request</param>
/// <param name="bytes">The file data</param>
/// <param name="fileName">The file name to use for the uploaded file</param>
/// <param name="contentType">The MIME type of the file to upload</param>
/// <returns>This request</returns>
public IRestRequest AddFile(string name, byte[] bytes, string fileName, string contentType = null)
{
return this.AddFile(FileParameter.Create(name, bytes, fileName, contentType));
}
/// <summary>
/// Adds the bytes to the Files collection with the specified file name and content type
/// </summary>
/// <param name="name">The parameter name to use in the request</param>
/// <param name="writer">A function that writes directly to the stream. Should NOT close the stream.</param>
/// <param name="fileName">The file name to use for the uploaded file</param>
/// <param name="contentLength">The length (in bytes) of the file content.</param>
/// <param name="contentType">The MIME type of the file to upload</param>
/// <returns>This request</returns>
public IRestRequest AddFile(string name, Action<Stream> writer, string fileName, long contentLength, string contentType = null)
{
return this.AddFile(new FileParameter
{
Name = name,
Writer = writer,
FileName = fileName,
ContentLength = contentLength,
ContentType = contentType
});
}
private IRestRequest AddFile(FileParameter file)
{
this.Files.Add(file);
return this;
}
/// <summary>
/// Add bytes to the Files collection as if it was a file of specific type
/// </summary>
/// <param name="name">A form parameter name</param>
/// <param name="bytes">The file data</param>
/// <param name="filename">The file name to use for the uploaded file</param>
/// <param name="contentType">Specific content type. Es: application/x-gzip </param>
/// <returns></returns>
public IRestRequest AddFileBytes(string name, byte[] bytes, string filename, string contentType = "application/x-gzip")
{
long length = bytes.Length;
return this.AddFile(new FileParameter
{
Name = name,
FileName = filename,
ContentLength = length,
ContentType = contentType,
Writer = s =>
{
using (StreamReader file = new StreamReader(new MemoryStream(bytes)))
{
file.BaseStream.CopyTo(s);
}
}
});
}
/// <summary>
/// Serializes obj to format specified by RequestFormat, but passes xmlNamespace if using the default XmlSerializer
/// The default format is XML. Change RequestFormat if you wish to use a different serialization format.
/// </summary>
/// <param name="obj">The object to serialize</param>
/// <param name="xmlNamespace">The XML namespace to use when serializing</param>
/// <returns>This request</returns>
public IRestRequest AddBody(object obj, string xmlNamespace)
{
string serialized;
string contentType;
switch (this.RequestFormat)
{
case DataFormat.Json:
serialized = this.JsonSerializer.Serialize(obj);
contentType = this.JsonSerializer.ContentType;
break;
case DataFormat.Xml:
this.XmlSerializer.Namespace = xmlNamespace;
serialized = this.XmlSerializer.Serialize(obj);
contentType = this.XmlSerializer.ContentType;
break;
default:
serialized = "";
contentType = "";
break;
}
// passing the content type as the parameter name because there can only be
// one parameter with ParameterType.RequestBody so name isn't used otherwise
// it's a hack, but it works :)
return this.AddParameter(contentType, serialized, ParameterType.RequestBody);
}
/// <summary>
/// Serializes obj to data format specified by RequestFormat and adds it to the request body.
/// The default format is XML. Change RequestFormat if you wish to use a different serialization format.
/// </summary>
/// <param name="obj">The object to serialize</param>
/// <returns>This request</returns>
public IRestRequest AddBody(object obj)
{
return this.AddBody(obj, "");
}
/// <summary>
/// Serializes obj to JSON format and adds it to the request body.
/// </summary>
/// <param name="obj">The object to serialize</param>
/// <returns>This request</returns>
public IRestRequest AddJsonBody(object obj)
{
this.RequestFormat = DataFormat.Json;
return this.AddBody(obj, "");
}
/// <summary>
/// Serializes obj to XML format and adds it to the request body.
/// </summary>
/// <param name="obj">The object to serialize</param>
/// <returns>This request</returns>
public IRestRequest AddXmlBody(object obj)
{
this.RequestFormat = DataFormat.Xml;
return this.AddBody(obj, "");
}
/// <summary>
/// Serializes obj to format specified by RequestFormat, but passes xmlNamespace if using the default XmlSerializer
/// Serializes obj to XML format and passes xmlNamespace then adds it to the request body.
/// </summary>
/// <param name="obj">The object to serialize</param>
/// <param name="xmlNamespace">The XML namespace to use when serializing</param>
/// <returns>This request</returns>
public IRestRequest AddXmlBody(object obj, string xmlNamespace)
{
this.RequestFormat = DataFormat.Xml;
return this.AddBody(obj, xmlNamespace);
}
/// <summary>
/// Calls AddParameter() for all public, readable properties specified in the includedProperties list
/// </summary>
/// <example>
/// request.AddObject(product, "ProductId", "Price", ...);
/// </example>
/// <param name="obj">The object with properties to add as parameters</param>
/// <param name="includedProperties">The names of the properties to include</param>
/// <returns>This request</returns>
public IRestRequest AddObject(object obj, params string[] includedProperties)
{
// automatically create parameters from object props
Type type = obj.GetType();
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo prop in props)
{
bool isAllowed = includedProperties.Length == 0 ||
(includedProperties.Length > 0 && includedProperties.Contains(prop.Name));
if (!isAllowed)
{
continue;
}
Type propType = prop.PropertyType;
object val = prop.GetValue(obj, null);
if (val == null)
{
continue;
}
if (propType.IsArray)
{
Type elementType = propType.GetElementType();
#if !WINDOWS_UWP
if (((Array) val).Length > 0 &&
elementType != null &&
(elementType.IsPrimitive || elementType.IsValueType || elementType == typeof(string)))
#else
if (((Array)val).Length > 0 &&
elementType != null &&
(elementType.GetTypeInfo().IsPrimitive || elementType.GetTypeInfo().IsValueType || elementType == typeof(string)))
#endif
{
// convert the array to an array of strings
string[] values = (from object item in ((Array) val)
select item.ToString()).ToArray<string>();
val = string.Join(",", values);
}
else
{
// try to cast it
val = string.Join(",", (string[]) val);
}
}
this.AddParameter(prop.Name, val);
}
return this;
}
/// <summary>
/// Calls AddParameter() for all public, readable properties of obj
/// </summary>
/// <param name="obj">The object with properties to add as parameters</param>
/// <returns>This request</returns>
public IRestRequest AddObject(object obj)
{
this.AddObject(obj, new string[] { });
return this;
}
/// <summary>
/// Add the parameter to the request
/// </summary>
/// <param name="p">Parameter to add</param>
/// <returns></returns>
public IRestRequest AddParameter(Parameter p)
{
this.Parameters.Add(p);
return this;
}
/// <summary>
/// Adds a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT)
/// </summary>
/// <param name="name">Name of the parameter</param>
/// <param name="value">Value of the parameter</param>
/// <returns>This request</returns>
public IRestRequest AddParameter(string name, object value)
{
return this.AddParameter(new Parameter
{
Name = name,
Value = value,
Type = ParameterType.GetOrPost
});
}
/// <summary>
/// Adds a parameter to the request. There are four types of parameters:
/// - GetOrPost: Either a QueryString value or encoded form value based on method
/// - HttpHeader: Adds the name/value pair to the HTTP request's Headers collection
/// - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId}
/// - RequestBody: Used by AddBody() (not recommended to use directly)
/// </summary>
/// <param name="name">Name of the parameter</param>
/// <param name="value">Value of the parameter</param>
/// <param name="type">The type of parameter to add</param>
/// <returns>This request</returns>
public IRestRequest AddParameter(string name, object value, ParameterType type)
{
return this.AddParameter(new Parameter
{
Name = name,
Value = value,
Type = type
});
}
/// <summary>
/// Adds a parameter to the request. There are four types of parameters:
/// - GetOrPost: Either a QueryString value or encoded form value based on method
/// - HttpHeader: Adds the name/value pair to the HTTP request's Headers collection
/// - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId}
/// - RequestBody: Used by AddBody() (not recommended to use directly)
/// </summary>
/// <param name="name">Name of the parameter</param>
/// <param name="value">Value of the parameter</param>
/// <param name="contentType">Content-Type of the parameter</param>
/// <param name="type">The type of parameter to add</param>
/// <returns>This request</returns>
public IRestRequest AddParameter(string name, object value, string contentType, ParameterType type)
{
return this.AddParameter(new Parameter
{
Name = name,
Value = value,
ContentType = contentType,
Type = type
});
}
public IRestRequest AddOrUpdateParameter(Parameter p)
{
if (Parameters.Any(param => param.Name == p.Name))
{
var parameter = this.Parameters.First(param => param.Name == p.Name);
parameter.Value = p.Value;
return this;
}
this.Parameters.Add(p);
return this;
}
public IRestRequest AddOrUpdateParameter(string name, object value)
{
return this.AddOrUpdateParameter(new Parameter
{
Name = name,
Value = value,
Type = ParameterType.GetOrPost
});
}
public IRestRequest AddOrUpdateParameter(string name, object value, ParameterType type)
{
return this.AddOrUpdateParameter(new Parameter
{
Name = name,
Value = value,
Type = type
});
}
public IRestRequest AddOrUpdateParameter(string name, object value, string contentType, ParameterType type)
{
return this.AddOrUpdateParameter(new Parameter
{
Name = name,
Value = value,
ContentType = contentType,
Type = type
});
}
/// <summary>
/// Shortcut to AddParameter(name, value, HttpHeader) overload
/// </summary>
/// <param name="name">Name of the header to add</param>
/// <param name="value">Value of the header to add</param>
/// <returns></returns>
public IRestRequest AddHeader(string name, string value)
{
#if !SILVERLIGHT
const string portSplit = @":\d+";
Func<string, bool> invalidHost =
host => Uri.CheckHostName(Regex.Split(host, portSplit)[0]) == UriHostNameType.Unknown;
if (name == "Host" && invalidHost(value))
{
throw new ArgumentException("The specified value is not a valid Host header string.", "value");
}
#endif
return this.AddParameter(name, value, ParameterType.HttpHeader);
}
/// <summary>
/// Shortcut to AddParameter(name, value, Cookie) overload
/// </summary>
/// <param name="name">Name of the cookie to add</param>
/// <param name="value">Value of the cookie to add</param>
/// <returns></returns>
public IRestRequest AddCookie(string name, string value)
{
return this.AddParameter(name, value, ParameterType.Cookie);
}
/// <summary>
/// Shortcut to AddParameter(name, value, UrlSegment) overload
/// </summary>
/// <param name="name">Name of the segment to add</param>
/// <param name="value">Value of the segment to add</param>
/// <returns></returns>
public IRestRequest AddUrlSegment(string name, string value)
{
return this.AddParameter(name, value, ParameterType.UrlSegment);
}
/// <summary>
/// Shortcut to AddParameter(name, value, UrlSegment) overload
/// </summary>
/// <param name="name">Name of the segment to add</param>
/// <param name="value">Value of the segment to add</param>
/// <returns></returns>
public IRestRequest AddUrlSegment(string name, object value)
{
return this.AddParameter(name, value, ParameterType.UrlSegment);
}
/// <summary>
/// Shortcut to AddParameter(name, value, QueryString) overload
/// </summary>
/// <param name="name">Name of the parameter to add</param>
/// <param name="value">Value of the parameter to add</param>
/// <returns></returns>
public IRestRequest AddQueryParameter(string name, string value)
{
return this.AddParameter(name, value, ParameterType.QueryString);
}
/// <summary>
/// Container of all HTTP parameters to be passed with the request.
/// See AddParameter() for explanation of the types of parameters that can be passed
/// </summary>
public List<Parameter> Parameters { get; private set; }
/// <summary>
/// Container of all the files to be uploaded with the request.
/// </summary>
public List<FileParameter> Files { get; private set; }
/// <summary>
/// Determines what HTTP method to use for this request. Supported methods: GET, POST, PUT, DELETE, HEAD, OPTIONS
/// Default is GET
/// </summary>
public Method Method { get; set; }
/// <summary>
/// The Resource URL to make the request against.
/// Tokens are substituted with UrlSegment parameters and match by name.
/// Should not include the scheme or domain. Do not include leading slash.
/// Combined with RestClient.BaseUrl to assemble final URL:
/// {BaseUrl}/{Resource} (BaseUrl is scheme + domain, e.g. http://example.com)
/// </summary>
/// <example>
/// // example for url token replacement
/// request.Resource = "Products/{ProductId}";
/// request.AddParameter("ProductId", 123, ParameterType.UrlSegment);
/// </example>
public string Resource { get; set; }
/// <summary>
/// Determines how to serialize the request body.
/// By default Xml is used.
/// </summary>
public DataFormat RequestFormat { get; set; }
/// <summary>
/// Used by the default deserializers to determine where to start deserializing from.
/// Can be used to skip container or root elements that do not have corresponding deserialzation targets.
/// </summary>
public string RootElement { get; set; }
/// <summary>
/// A function to run prior to deserializing starting (e.g. change settings if error encountered)
/// </summary>
public Action<IRestResponse> OnBeforeDeserialization { get; set; }
/// <summary>
/// Used by the default deserializers to explicitly set which date format string to use when parsing dates.
/// </summary>
public string DateFormat { get; set; }
/// <summary>
/// Used by XmlDeserializer. If not specified, XmlDeserializer will flatten response by removing namespaces from element names.
/// </summary>
public string XmlNamespace { get; set; }
/// <summary>
/// In general you would not need to set this directly. Used by the NtlmAuthenticator.
/// </summary>
public ICredentials Credentials { get; set; }
/// <summary>
/// Gets or sets a user-defined state object that contains information about a request and which can be later
/// retrieved when the request completes.
/// </summary>
public object UserState { get; set; }
/// <summary>
/// Timeout in milliseconds to be used for the request. This timeout value overrides a timeout set on the RestClient.
/// </summary>
public int Timeout { get; set; }
/// <summary>
/// The number of milliseconds before the writing or reading times out. This timeout value overrides a timeout set on the RestClient.
/// </summary>
public int ReadWriteTimeout { get; set; }
/// <summary>
/// Internal Method so that RestClient can increase the number of attempts
/// </summary>
public void IncreaseNumAttempts()
{
this.Attempts++;
}
/// <summary>
/// How many attempts were made to send this Request?
/// </summary>
/// <remarks>
/// This Number is incremented each time the RestClient sends the request.
/// Useful when using Asynchronous Execution with Callbacks
/// </remarks>
public int Attempts { get; private set; }
}
}