forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonHttpClient.cs
More file actions
886 lines (703 loc) · 32.4 KB
/
JsonHttpClient.cs
File metadata and controls
886 lines (703 loc) · 32.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
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
// Copyright (c) Service Stack LLC. All Rights Reserved.
// License: https://raw.github.com/ServiceStack/ServiceStack/master/license.txt
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ServiceStack.Logging;
using ServiceStack.Serialization;
using ServiceStack.Text;
using ServiceStack.Web;
namespace ServiceStack
{
public class JsonHttpClient : IServiceClient, IJsonServiceClient, IHasCookieContainer
{
public static ILog log = LogManager.GetLogger(typeof(JsonHttpClient));
public static Func<HttpMessageHandler> GlobalHttpMessageHandlerFactory { get; set; }
public HttpMessageHandler HttpMessageHandler { get; set; }
public HttpClient HttpClient { get; set; }
public CookieContainer CookieContainer { get; set; }
public ResultsFilterHttpDelegate ResultsFilter { get; set; }
public ResultsFilterHttpResponseDelegate ResultsFilterResponse { get; set; }
public const string DefaultHttpMethod = "POST";
public static string DefaultUserAgent = "ServiceStack .NET HttpClient " + Env.ServiceStackVersion;
public string BaseUri { get; set; }
public string Format = "json";
public string ContentType = MimeTypes.Json;
public string SyncReplyBaseUri { get; set; }
public string AsyncOneWayBaseUri { get; set; }
public int Version { get; set; }
public string SessionId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public bool AlwaysSendBasicAuthHeader { get; set; }
public CancellationTokenSource CancelTokenSource { get; set; }
/// <summary>
/// Gets the collection of headers to be added to outgoing requests.
/// </summary>
public INameValueCollection Headers { get; private set; }
public void SetBaseUri(string baseUri)
{
this.BaseUri = baseUri;
this.SyncReplyBaseUri = baseUri.WithTrailingSlash() + Format + "/reply/";
this.AsyncOneWayBaseUri = baseUri.WithTrailingSlash() + Format + "/oneway/";
}
public JsonHttpClient(string baseUri) : this()
{
SetBaseUri(baseUri);
}
public JsonHttpClient()
{
this.Headers = PclExportClient.Instance.NewNameValueCollection();
this.CookieContainer = new CookieContainer();
}
public void SetCredentials(string userName, string password)
{
this.UserName = userName;
this.Password = password;
}
public virtual string GetBaseUrl(string relativeOrAbsoluteUrl)
{
return relativeOrAbsoluteUrl.StartsWith("http:")
|| relativeOrAbsoluteUrl.StartsWith("https:")
? relativeOrAbsoluteUrl
: this.BaseUri.CombineWith(relativeOrAbsoluteUrl);
}
public HttpClient GetHttpClient()
{
//Should reuse same instance: http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/4e12d8e2-e0bf-4654-ac85-3d49b07b50af/
if (HttpClient != null)
return HttpClient;
if (HttpMessageHandler == null && GlobalHttpMessageHandlerFactory != null)
HttpMessageHandler = GlobalHttpMessageHandlerFactory();
var baseUri = BaseUri != null ? new Uri(BaseUri) : null;
return HttpClient = HttpMessageHandler != null
? new HttpClient(HttpMessageHandler) { BaseAddress = baseUri }
: new HttpClient(new HttpClientHandler {
UseCookies = true,
CookieContainer = CookieContainer,
UseDefaultCredentials = true
}) {
BaseAddress = baseUri
};
}
private int activeAsyncRequests = 0;
public Task<TResponse> SendAsync<TResponse>(string httpMethod, string absoluteUrl, object request)
{
if (ResultsFilter != null)
{
var response = ResultsFilter(typeof(TResponse), httpMethod, absoluteUrl, request);
if (response is TResponse)
{
var tcs = new TaskCompletionSource<TResponse>();
tcs.SetResult((TResponse)response);
return tcs.Task;
}
}
var client = GetHttpClient();
if (AlwaysSendBasicAuthHeader)
AddBasicAuth(client);
this.PopulateRequestMetadata(request);
var httpReq = new HttpRequestMessage(new HttpMethod(httpMethod), absoluteUrl);
if (httpMethod.HasRequestBody() && request != null)
{
foreach (var name in Headers.AllKeys)
{
httpReq.Headers.Add(name, Headers[name]);
}
var httpContent = request as HttpContent;
if (httpContent != null)
{
httpReq.Content = httpContent;
}
else
{
using (__requestAccess())
{
httpReq.Content = new StringContent(request.ToJson(), Encoding.UTF8, ContentType);
}
}
}
httpReq.Headers.Add(HttpHeaders.Accept, ContentType);
ApplyWebRequestFilters(httpReq);
Interlocked.Increment(ref activeAsyncRequests);
if (CancelTokenSource == null)
CancelTokenSource = new CancellationTokenSource();
var sendAsyncTask = client.SendAsync(httpReq, CancelTokenSource.Token);
if (typeof(TResponse) == typeof(HttpResponseMessage))
{
return (Task<TResponse>)(object)sendAsyncTask;
}
return sendAsyncTask
.ContinueWith(responseTask =>
{
var httpRes = responseTask.Result;
ApplyWebResponseFilters(httpRes);
if (typeof(TResponse) == typeof(byte[]))
{
return httpRes.Content.ReadAsByteArrayAsync().ContinueWith(task =>
{
ThrowIfError<TResponse>(task, httpRes, request, absoluteUrl, task.Result);
var response = (TResponse)(object)task.Result;
if (ResultsFilterResponse != null)
ResultsFilterResponse(httpRes, response, httpMethod, absoluteUrl, request);
return response;
});
}
if (typeof(TResponse) == typeof(Stream))
{
return httpRes.Content.ReadAsStreamAsync().ContinueWith(task =>
{
ThrowIfError<TResponse>(task, httpRes, request, absoluteUrl, task.Result);
var response = (TResponse)(object)task.Result;
if (ResultsFilterResponse != null)
ResultsFilterResponse(httpRes, response, httpMethod, absoluteUrl, request);
return response;
});
}
return httpRes.Content.ReadAsStringAsync().ContinueWith(task =>
{
ThrowIfError<TResponse>(task, httpRes, request, absoluteUrl, task.Result);
var body = task.Result;
var response = body.FromJson<TResponse>();
if (ResultsFilterResponse != null)
ResultsFilterResponse(httpRes, response, httpMethod, absoluteUrl, request);
return response;
});
}).Unwrap();
}
private void DisposeCancelToken()
{
if (Interlocked.Decrement(ref activeAsyncRequests) > 0) return;
if (CancelTokenSource == null) return;
CancelTokenSource.Dispose();
CancelTokenSource = null;
}
public virtual void SerializeToStream(IRequest requestContext, object request, Stream stream)
{
JsonDataContractSerializer.Instance.SerializeToStream(request, stream);
}
private class AccessToken
{
private string token;
internal static readonly AccessToken __accessToken =
new AccessToken("lUjBZNG56eE9yd3FQdVFSTy9qeGl5dlI5RmZwamc4U05udl000");
private AccessToken(string token)
{
this.token = token;
}
}
protected static IDisposable __requestAccess()
{
return LicenseUtils.RequestAccess(AccessToken.__accessToken, LicenseFeature.Client, LicenseFeature.Text);
}
public Action<HttpRequestMessage> RequestFilter { get; set; }
public static Action<HttpRequestMessage> GlobalRequestFilter { get; set; }
private void ApplyWebRequestFilters(HttpRequestMessage httpReq)
{
if (RequestFilter != null)
RequestFilter(httpReq);
if (GlobalRequestFilter != null)
GlobalRequestFilter(httpReq);
}
public Action<HttpResponseMessage> ResponseFilter { get; set; }
public static Action<HttpResponseMessage> GlobalResponseFilter { get; set; }
private void ApplyWebResponseFilters(HttpResponseMessage httpRes)
{
if (ResponseFilter != null)
ResponseFilter(httpRes);
if (GlobalResponseFilter != null)
GlobalResponseFilter(httpRes);
}
private void ThrowIfError<TResponse>(Task task, HttpResponseMessage httpRes, object request, string requestUri, object response)
{
DisposeCancelToken();
if (task.IsFaulted)
throw CreateException<TResponse>(httpRes, task.Exception);
if (!httpRes.IsSuccessStatusCode)
ThrowResponseTypeException<TResponse>(httpRes, request, requestUri, response);
}
private void AddBasicAuth(HttpClient client)
{
if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password)) return;
var byteArray = Encoding.UTF8.GetBytes("{0}:{1}".Fmt(UserName, Password));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
}
protected T ResultFilter<T>(T response, HttpResponseMessage httpRes, string httpMethod, string requestUri, object request)
{
if (ResultsFilterResponse != null)
{
ResultsFilterResponse(httpRes, response, httpMethod, requestUri, request);
}
return response;
}
private static WebServiceException CreateException<TResponse>(HttpResponseMessage httpRes, Exception ex)
{
return new WebServiceException();
}
readonly ConcurrentDictionary<Type, Action<HttpResponseMessage, object, string, object>> ResponseHandlers
= new ConcurrentDictionary<Type, Action<HttpResponseMessage, object, string, object>>();
private void ThrowResponseTypeException<TResponse>(HttpResponseMessage httpRes, object request, string requestUri, object response)
{
var responseType = WebRequestUtils.GetErrorResponseDtoType<TResponse>(request);
Action<HttpResponseMessage, object, string, object> responseHandler;
if (!ResponseHandlers.TryGetValue(responseType, out responseHandler))
{
var mi = GetType().GetInstanceMethod("ThrowWebServiceException")
.MakeGenericMethod(new[] { responseType });
responseHandler = (Action<HttpResponseMessage, object, string, object>)mi.CreateDelegate(
typeof(Action<HttpResponseMessage, object, string, object>), this);
ResponseHandlers[responseType] = responseHandler;
}
responseHandler(httpRes, request, requestUri, response);
}
public byte[] GetResponseBytes(object response)
{
var stream = response as Stream;
if (stream != null)
return stream.ReadFully();
var bytes = response as byte[];
if (bytes != null)
return bytes;
var str = response as string;
if (str != null)
return str.ToUtf8Bytes();
return null;
}
public void ThrowWebServiceException<TResponse>(HttpResponseMessage httpRes, object request, string requestUri, object response)
{
if (log.IsDebugEnabled)
{
log.DebugFormat("Status Code : {0}", httpRes.StatusCode);
log.DebugFormat("Status Description : {0}", httpRes.ReasonPhrase);
}
var serviceEx = new WebServiceException(httpRes.ReasonPhrase)
{
StatusCode = (int)httpRes.StatusCode,
StatusDescription = httpRes.ReasonPhrase,
ResponseHeaders = httpRes.Headers.ToWebHeaderCollection()
};
try
{
var contentType = httpRes.GetContentType();
var bytes = GetResponseBytes(response);
if (bytes != null)
{
if (string.IsNullOrEmpty(contentType) || contentType.MatchesContentType(ContentType))
{
using (__requestAccess())
{
var stream = MemoryStreamFactory.GetStream(bytes);
serviceEx.ResponseBody = bytes.FromUtf8Bytes();
serviceEx.ResponseDto = JsonSerializer.DeserializeFromStream<TResponse>(stream);
if (stream.CanRead)
stream.Dispose(); //alt ms throws when you dispose twice
}
}
else
{
serviceEx.ResponseBody = bytes.FromUtf8Bytes();
}
}
}
catch (Exception innerEx)
{
// Oh, well, we tried
throw new WebServiceException(httpRes.ReasonPhrase, innerEx)
{
StatusCode = (int)httpRes.StatusCode,
StatusDescription = httpRes.ReasonPhrase,
ResponseBody = serviceEx.ResponseBody
};
}
//Escape deserialize exception handling and throw here
throw serviceEx;
//var authEx = ex as AuthenticationException;
//if (authEx != null)
//{
// throw WebRequestUtils.CreateCustomException(requestUri, authEx);
//}
}
public T GetSyncResponse<T>(Task<T> task)
{
try
{
return task.Result;
}
catch (Exception ex)
{
throw ex.UnwrapIfSingleException();
}
}
public void WaitSyncResponse(Task task)
{
try
{
task.Wait();
}
catch (Exception ex)
{
throw ex.UnwrapIfSingleException();
}
}
public virtual Task<TResponse> SendAsync<TResponse>(IReturn<TResponse> requestDto)
{
return SendAsync<TResponse>((object)requestDto);
}
public virtual Task<TResponse> SendAsync<TResponse>(object requestDto)
{
var requestUri = this.SyncReplyBaseUri.WithTrailingSlash() + requestDto.GetType().Name;
return SendAsync<TResponse>(HttpMethods.Post, requestUri, requestDto);
}
public virtual Task<HttpResponseMessage> SendAsync(IReturnVoid requestDto)
{
return SendAsync<HttpResponseMessage>(requestDto);
}
public virtual Task<List<TResponse>> SendAllAsync<TResponse>(IEnumerable<IReturn<TResponse>> requests)
{
var elType = requests.GetType().GetCollectionType();
var requestUri = this.SyncReplyBaseUri.WithTrailingSlash() + elType.Name + "[]";
return SendAsync<List<TResponse>>(HttpMethods.Post, requestUri, requests);
}
public Task<TResponse> GetAsync<TResponse>(IReturn<TResponse> requestDto)
{
return GetAsync<TResponse>(requestDto.ToUrl(HttpMethods.Get, Format));
}
public Task<TResponse> GetAsync<TResponse>(object requestDto)
{
return GetAsync<TResponse>(requestDto.ToUrl(HttpMethods.Get, Format));
}
public Task<TResponse> GetAsync<TResponse>(string relativeOrAbsoluteUrl)
{
return SendAsync<TResponse>(HttpMethods.Get, GetBaseUrl(relativeOrAbsoluteUrl), null);
}
public Task GetAsync(IReturnVoid requestDto)
{
return GetAsync<byte[]>(requestDto.ToUrl(HttpMethods.Get, Format));
}
public Task<TResponse> DeleteAsync<TResponse>(IReturn<TResponse> requestDto)
{
return DeleteAsync<TResponse>(requestDto.ToUrl(HttpMethods.Delete, Format));
}
public Task<TResponse> DeleteAsync<TResponse>(object requestDto)
{
return DeleteAsync<TResponse>(requestDto.ToUrl(HttpMethods.Delete, Format));
}
public Task<TResponse> DeleteAsync<TResponse>(string relativeOrAbsoluteUrl)
{
return SendAsync<TResponse>(HttpMethods.Delete, GetBaseUrl(relativeOrAbsoluteUrl), null);
}
public Task DeleteAsync(IReturnVoid requestDto)
{
return DeleteAsync<byte[]>(requestDto.ToUrl(HttpMethods.Delete, Format));
}
public Task<TResponse> PostAsync<TResponse>(IReturn<TResponse> requestDto)
{
return PostAsync<TResponse>(requestDto.ToUrl(HttpMethods.Post, Format), requestDto);
}
public Task<TResponse> PostAsync<TResponse>(object requestDto)
{
return PostAsync<TResponse>(requestDto.ToUrl(HttpMethods.Post, Format), requestDto);
}
public Task<TResponse> PostAsync<TResponse>(string relativeOrAbsoluteUrl, object request)
{
return SendAsync<TResponse>(HttpMethods.Post, GetBaseUrl(relativeOrAbsoluteUrl), request);
}
public Task PostAsync(IReturnVoid requestDto)
{
return PostAsync<byte[]>(requestDto.ToUrl(HttpMethods.Post, Format), requestDto);
}
public Task<TResponse> PutAsync<TResponse>(IReturn<TResponse> requestDto)
{
return PutAsync<TResponse>(requestDto.ToUrl(HttpMethods.Put, Format), requestDto);
}
public Task<TResponse> PutAsync<TResponse>(object requestDto)
{
return PutAsync<TResponse>(requestDto.ToUrl(HttpMethods.Put, Format), requestDto);
}
public Task<TResponse> PutAsync<TResponse>(string relativeOrAbsoluteUrl, object request)
{
return SendAsync<TResponse>(HttpMethods.Put, GetBaseUrl(relativeOrAbsoluteUrl), request);
}
public Task PutAsync(IReturnVoid requestDto)
{
return PutAsync<byte[]>(requestDto.ToUrl(HttpMethods.Put, Format), requestDto);
}
public Task<TResponse> CustomMethodAsync<TResponse>(string httpVerb, IReturn<TResponse> requestDto)
{
if (!HttpMethods.HasVerb(httpVerb))
throw new NotSupportedException("Unknown HTTP Method is not supported: " + httpVerb);
var requestBody = httpVerb.HasRequestBody() ? requestDto : null;
return SendAsync<TResponse>(httpVerb, GetBaseUrl(requestDto.ToUrl(httpVerb, Format)), requestBody);
}
public Task<TResponse> CustomMethodAsync<TResponse>(string httpVerb, object requestDto)
{
if (!HttpMethods.HasVerb(httpVerb))
throw new NotSupportedException("Unknown HTTP Method is not supported: " + httpVerb);
var requestBody = httpVerb.HasRequestBody() ? requestDto : null;
return SendAsync<TResponse>(httpVerb, GetBaseUrl(requestDto.ToUrl(httpVerb, Format)), requestBody);
}
public Task CustomMethodAsync(string httpVerb, IReturnVoid requestDto)
{
if (!HttpMethods.HasVerb(httpVerb))
throw new NotSupportedException("Unknown HTTP Method is not supported: " + httpVerb);
var requestBody = httpVerb.HasRequestBody() ? requestDto : null;
return SendAsync<byte[]>(httpVerb, GetBaseUrl(requestDto.ToUrl(httpVerb, Format)), requestBody);
}
public Task<TResponse> CustomMethodAsync<TResponse>(string httpVerb, string relativeOrAbsoluteUrl, object request)
{
if (!HttpMethods.HasVerb(httpVerb))
throw new NotSupportedException("Unknown HTTP Method is not supported: " + httpVerb);
var requestBody = httpVerb.HasRequestBody() ? request : null;
return SendAsync<TResponse>(httpVerb, GetBaseUrl(relativeOrAbsoluteUrl), requestBody);
}
public void SendOneWay(object requestDto)
{
var requestUri = this.AsyncOneWayBaseUri.WithTrailingSlash() + requestDto.GetType().Name;
SendOneWay(HttpMethods.Post, requestUri, requestDto);
}
public void SendOneWay(string relativeOrAbsoluteUri, object request)
{
SendOneWay(HttpMethods.Post, relativeOrAbsoluteUri, request);
}
public virtual void SendOneWay(string httpMethod, string relativeOrAbsoluteUrl, object requestDto)
{
var requestUri = GetBaseUrl(relativeOrAbsoluteUrl);
SendAsync<byte[]>(httpMethod, requestUri, requestDto).Wait();
}
public void SendAllOneWay(IEnumerable<object> requests)
{
var elType = requests.GetType().GetCollectionType();
var requestUri = this.AsyncOneWayBaseUri.WithTrailingSlash() + elType.Name + "[]";
SendOneWay(HttpMethods.Post, requestUri, requests);
}
public void ClearCookies()
{
CookieContainer = new CookieContainer();
HttpClient = null;
GetHttpClient();
}
public Dictionary<string, string> GetCookieValues()
{
return CookieContainer.ToDictionary(BaseUri);
}
public void SetCookie(string name, string value, TimeSpan? expiresIn = null)
{
this.SetCookie(HttpClient.BaseAddress, name, value,
expiresIn != null ? DateTime.UtcNow.Add(expiresIn.Value) : (DateTime?)null);
}
public void Get(IReturnVoid request)
{
WaitSyncResponse(GetAsync(request));
}
public TResponse Get<TResponse>(IReturn<TResponse> request)
{
return GetSyncResponse(GetAsync(request));
}
public TResponse Get<TResponse>(object request)
{
return GetSyncResponse(GetAsync<TResponse>(request));
}
public TResponse Get<TResponse>(string relativeOrAbsoluteUrl)
{
return GetSyncResponse(GetAsync<TResponse>(relativeOrAbsoluteUrl));
}
public IEnumerable<TResponse> GetLazy<TResponse>(IReturn<QueryResponse<TResponse>> queryDto)
{
throw new NotImplementedException();
}
public void Delete(IReturnVoid requestDto)
{
WaitSyncResponse(DeleteAsync(requestDto));
}
public TResponse Delete<TResponse>(IReturn<TResponse> request)
{
return GetSyncResponse(DeleteAsync(request));
}
public TResponse Delete<TResponse>(object request)
{
return GetSyncResponse(DeleteAsync<TResponse>(request));
}
public TResponse Delete<TResponse>(string relativeOrAbsoluteUrl)
{
return GetSyncResponse(DeleteAsync<TResponse>(relativeOrAbsoluteUrl));
}
public void Post(IReturnVoid requestDto)
{
WaitSyncResponse(PostAsync(requestDto));
}
public TResponse Post<TResponse>(IReturn<TResponse> request)
{
return GetSyncResponse(PostAsync(request));
}
public TResponse Post<TResponse>(object request)
{
return GetSyncResponse(PostAsync<TResponse>(request));
}
public TResponse Post<TResponse>(string relativeOrAbsoluteUrl, object request)
{
return GetSyncResponse(PostAsync<TResponse>(relativeOrAbsoluteUrl, request));
}
public void Put(IReturnVoid requestDto)
{
WaitSyncResponse(PutAsync(requestDto));
}
public TResponse Put<TResponse>(IReturn<TResponse> request)
{
return GetSyncResponse(PutAsync(request));
}
public TResponse Put<TResponse>(object request)
{
return GetSyncResponse(PutAsync<TResponse>(request));
}
public TResponse Put<TResponse>(string relativeOrAbsoluteUrl, object request)
{
return GetSyncResponse(PutAsync<TResponse>(relativeOrAbsoluteUrl, request));
}
public void Patch(IReturnVoid request)
{
WaitSyncResponse(SendAsync<byte[]>(HttpMethods.Patch, request.ToUrl(HttpMethods.Patch, Format), null));
}
public TResponse Patch<TResponse>(IReturn<TResponse> request)
{
return GetSyncResponse(SendAsync<TResponse>(HttpMethods.Patch, request.ToUrl(HttpMethods.Patch, Format), request));
}
public TResponse Patch<TResponse>(object request)
{
return GetSyncResponse(SendAsync<TResponse>(HttpMethods.Patch, request.ToUrl(HttpMethods.Patch, Format), request));
}
public TResponse Patch<TResponse>(string relativeOrAbsoluteUrl, object request)
{
return GetSyncResponse(SendAsync<TResponse>(HttpMethods.Patch, relativeOrAbsoluteUrl, request));
}
public void CustomMethod(string httpVerb, IReturnVoid request)
{
WaitSyncResponse(SendAsync<byte[]>(httpVerb, request.ToUrl(httpVerb, Format), request));
}
public TResponse CustomMethod<TResponse>(string httpVerb, IReturn<TResponse> request)
{
return GetSyncResponse(SendAsync<TResponse>(httpVerb, request.ToUrl(httpVerb, Format), request));
}
public TResponse CustomMethod<TResponse>(string httpVerb, object request)
{
return GetSyncResponse(SendAsync<TResponse>(httpVerb, request.ToUrl(httpVerb, Format), null));
}
public Task<TResponse> PostFileAsync<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, string mimeType = null)
{
var content = new MultipartFormDataContent();
var fileBytes = fileToUpload.ReadFully();
var fileContent = new ByteArrayContent(fileBytes, 0, fileBytes.Length);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file",
FileName = fileName
};
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType ?? MimeTypes.GetMimeType(fileName));
content.Add(fileContent, "file", fileName);
return SendAsync<TResponse>(HttpMethods.Post, GetBaseUrl(relativeOrAbsoluteUrl), content)
.ContinueWith(t => { content.Dispose(); fileContent.Dispose(); return t.Result; },
TaskContinuationOptions.ExecuteSynchronously);
}
public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, string mimeType)
{
return GetSyncResponse(PostFileAsync<TResponse>(relativeOrAbsoluteUrl, fileToUpload, fileName, mimeType));
}
public Task<TResponse> PostFileWithRequestAsync<TResponse>(Stream fileToUpload, string fileName, object request, string fieldName = "upload")
{
return PostFileWithRequestAsync<TResponse>(request.ToPostUrl(), fileToUpload, fileName, request, fieldName);
}
public TResponse PostFileWithRequest<TResponse>(Stream fileToUpload, string fileName, object request, string fieldName = "upload")
{
return GetSyncResponse(PostFileWithRequestAsync<TResponse>(fileToUpload, fileName, request, fileName));
}
public Task<TResponse> PostFileWithRequestAsync<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName,
object request, string fieldName = "upload")
{
var queryString = QueryStringSerializer.SerializeToString(request);
var nameValueCollection = PclExportClient.Instance.ParseQueryString(queryString);
var content = new MultipartFormDataContent();
foreach (string key in nameValueCollection)
{
var value = nameValueCollection[key];
content.Add(new StringContent(value), "\"{0}\"".Fmt(key));
}
var fileBytes = fileToUpload.ReadFully();
var fileContent = new ByteArrayContent(fileBytes, 0, fileBytes.Length);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file",
FileName = fileName
};
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(MimeTypes.GetMimeType(fileName));
content.Add(fileContent, "file", fileName);
return SendAsync<TResponse>(HttpMethods.Post, GetBaseUrl(relativeOrAbsoluteUrl), content)
.ContinueWith(t => { content.Dispose(); fileContent.Dispose(); return t.Result; },
TaskContinuationOptions.ExecuteSynchronously);
}
public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName,
object request, string fieldName = "upload")
{
return GetSyncResponse(PostFileWithRequestAsync<TResponse>(relativeOrAbsoluteUrl, fileToUpload, fileName, request, fileName));
}
public TResponse Send<TResponse>(object request)
{
return GetSyncResponse(SendAsync<TResponse>(request));
}
public virtual TResponse Send<TResponse>(IReturn<TResponse> request)
{
return Send<TResponse>((object)request);
}
public virtual void Send(IReturnVoid request)
{
SendOneWay(request);
}
public List<TResponse> SendAll<TResponse>(IEnumerable<IReturn<TResponse>> requests)
{
return GetSyncResponse(SendAllAsync(requests));
}
public void CancelAsync()
{
CancelTokenSource.Cancel();
}
public void Dispose()
{
}
}
public delegate object ResultsFilterHttpDelegate(Type responseType, string httpMethod, string requestUri, object request);
public delegate void ResultsFilterHttpResponseDelegate(HttpResponseMessage webResponse, object response, string httpMethod, string requestUri, object request);
public static class JsonHttpClientUtils
{
public static Dictionary<string, string> ToDictionary(this HttpResponseHeaders headers)
{
var to = new Dictionary<string, string>();
foreach (var header in headers)
{
to[header.Key] = string.Join(", ", header.Value);
}
return to;
}
public static WebHeaderCollection ToWebHeaderCollection(this HttpResponseHeaders headers)
{
var to = new WebHeaderCollection();
foreach (var header in headers)
{
to[header.Key] = string.Join(", ", header.Value);
}
return to;
}
public static string GetContentType(this HttpResponseMessage httpRes)
{
IEnumerable<string> values;
return httpRes.Headers.TryGetValues(HttpHeaders.ContentType, out values)
? values.FirstOrDefault()
: null;
}
}
}