You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Readarr/src/NzbDrone.Common/Http/HttpResponse.cs

107 lines
3.5 KiB

10 years ago
using System;
using System.Collections.Generic;
10 years ago
using System.Net;
using System.Text.RegularExpressions;
using NzbDrone.Common.Extensions;
10 years ago
using NzbDrone.Common.Serializer;
namespace NzbDrone.Common.Http
{
public class HttpResponse
{
private static readonly Regex RegexSetCookie = new Regex("^(.*?)=(.*?)(?:;|$)", RegexOptions.Compiled);
public HttpResponse(HttpRequest request, HttpHeader headers, byte[] binaryData, HttpStatusCode statusCode = HttpStatusCode.OK)
10 years ago
{
Request = request;
Headers = headers;
ResponseData = binaryData;
StatusCode = statusCode;
}
public HttpResponse(HttpRequest request, HttpHeader headers, string content, HttpStatusCode statusCode = HttpStatusCode.OK)
{
Request = request;
Headers = headers;
ResponseData = Headers.GetEncodingFromContentType().GetBytes(content);
_content = content;
10 years ago
StatusCode = statusCode;
}
public HttpRequest Request { get; private set; }
public HttpHeader Headers { get; private set; }
public HttpStatusCode StatusCode { get; private set; }
public byte[] ResponseData { get; private set; }
private string _content;
public string Content
{
get
{
if (_content == null)
{
_content = Headers.GetEncodingFromContentType().GetString(ResponseData);
}
return _content;
}
}
public bool HasHttpError => (int)StatusCode >= 400;
10 years ago
public bool HasHttpRedirect => StatusCode == HttpStatusCode.Moved ||
StatusCode == HttpStatusCode.MovedPermanently ||
StatusCode == HttpStatusCode.Found ||
StatusCode == HttpStatusCode.TemporaryRedirect ||
StatusCode == HttpStatusCode.RedirectMethod ||
StatusCode == HttpStatusCode.SeeOther;
public string[] GetCookieHeaders()
{
return Headers.GetValues("Set-Cookie") ?? new string[0];
}
public Dictionary<string, string> GetCookies()
{
var result = new Dictionary<string, string>();
var setCookieHeaders = GetCookieHeaders();
foreach (var cookie in setCookieHeaders)
{
var match = RegexSetCookie.Match(cookie);
if (match.Success)
{
result[match.Groups[1].Value] = match.Groups[2].Value;
}
}
return result;
}
10 years ago
public override string ToString()
{
var result = string.Format("Res: [{0}] {1}: {2}.{3}", Request.Method, Request.Url, (int)StatusCode, StatusCode);
10 years ago
if (HasHttpError && Headers.ContentType.IsNotNullOrWhiteSpace() && !Headers.ContentType.Equals("text/html", StringComparison.InvariantCultureIgnoreCase))
10 years ago
{
result += Environment.NewLine + Content;
}
return result;
}
}
public class HttpResponse<T> : HttpResponse
where T : new()
10 years ago
{
public HttpResponse(HttpResponse response)
: base(response.Request, response.Headers, response.ResponseData, response.StatusCode)
10 years ago
{
Resource = Json.Deserialize<T>(response.Content);
}
public T Resource { get; private set; }
}
}