blob: 8b654dd611c444c60fcdb7f1222a46cd44abeecf (
plain)
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
|
using Google.Protobuf;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Tango.PMR.Synchronization;
namespace Tango.Transport.Web
{
public class JsonWebClient : ITransportWebClient
{
private HttpClient _httpClient;
public JsonWebClient()
{
_httpClient = new HttpClient();
}
public void Dispose()
{
throw new NotImplementedException();
}
public Task<Response> Post<Request, Response>(String url, Request request) where Request : class, IMessage where Response : class, IMessage
{
return Task.Factory.StartNew<Response>(() =>
{
var req = new ByteArrayContent(Encoding.UTF8.GetBytes(request.ToString()));
req.Headers.Add("Content-Type", "application/json");
var response = _httpClient.PostAsync(url, req).Result;
var data = response.Content.ReadAsStringAsync().Result;
Response dummy = Activator.CreateInstance<Response>() as Response;
return dummy.GetParser().ParseJson(data) as Response;
});
}
public Task<Response> PostJson<Request, Response>(String url, Request request) where Request : class where Response : class
{
return Task.Factory.StartNew<Response>(() =>
{
var req = new ByteArrayContent(Encoding.UTF8.GetBytes(request.ToJsonString()));
req.Headers.Add("Content-Type", "application/json");
var response = _httpClient.PostAsync(url, req).Result;
var data = response.Content.ReadAsStringAsync().Result;
try
{
response.EnsureSuccessStatusCode();
}
catch (HttpRequestException ex)
{
throw new HttpRequestException(ex.Message + " " + JObject.Parse(data).GetValue("Message"));
}
return JsonConvert.DeserializeObject<Response>(data);
});
}
}
}
|