Statistics
| Branch: | Revision:

root / trunk / Pithos.Network / WebExtensions.cs @ e394ef0f

History | View | Annotate | Download (1.6 kB)

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using System.Net;
6
using System.IO;
7
using log4net;
8

    
9
namespace Pithos.Network
10
{
11
    public static class WebExtensions
12
    {
13
        public static string ReadToEnd(this HttpWebResponse response)
14
        {
15
            using (var stream = response.GetResponseStream())
16
            {
17
                if (stream == null)
18
                    return null;
19
                using (var reader = new StreamReader(stream))
20
                {
21
                    var body = reader.ReadToEnd();
22
                    return body;
23
                }
24
            }
25
        }
26
    
27
        public static void LogError(this ILog log,HttpWebResponse response)
28
        {
29
            if (log.IsDebugEnabled)
30
            {
31
                if (response != null)
32
                {
33
                    var body = response.ReadToEnd();
34
                    log.ErrorFormat("Headers:\n{0}\nBody:{1}", response.Headers,body);
35
                }
36
            }
37
        }
38

    
39
        public static TextReader GetLoggedReader(this Stream stream, ILog log, long contentLength)
40
        {
41
            var reader = new StreamReader(stream);
42
            if (!log.IsDebugEnabled)
43
                return reader;
44
            
45
            using (reader)
46
            {
47
                var buffer=new char[contentLength];
48
                var read=reader.Read(buffer, 0, (int)contentLength);
49
                var body = new string(buffer,0,read); //reader.ReadToEnd();
50
                log.DebugFormat("JSON response: {0}", body);
51
                return new StringReader(body);
52
            }
53
        }
54
    }
55
}