aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Transport/Web/ProtoWebClient.cs
blob: 43ff482fd08ec114f3ac8f00e7556f4f6795f6c1 (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
using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Tango.Transport.Web
{
    public class ProtoWebClient : ITransportWebClient
    {
        private HttpClient _httpClient;

        public ProtoWebClient()
        {
            _httpClient = new HttpClient();
        }

        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(request.ToByteArray());
                req.Headers.Add("Content-Type", "application/x-protobuf");

                var response = _httpClient.PostAsync(url, req).Result;
                var data = response.Content.ReadAsByteArrayAsync().Result;

                Response dummy = Activator.CreateInstance<Response>() as Response;

                return dummy.GetParser().ParseFrom(data) as Response;
            });
        }

        public void Dispose()
        {
            _httpClient.Dispose();
        }
    }
}