Пример #1
0
 /// <summary>
 /// Authenticates the fluent http request using http basic authentication.
 /// </summary>
 /// <param name="fluentHttpRequest">
 /// The fluent http request.
 /// </param>
 public void Authenticate(FluentHttpRequest fluentHttpRequest)
 {
     fluentHttpRequest.Headers(
         headers =>
         headers.Add(
             "Authorization",
             string.Concat("Basic ",
                           Convert.ToBase64String(
                               Encoding.UTF8.GetBytes(string.Format("{0}:{1}", Username, Password))))));
 }
Пример #2
0
 /// <summary>
 /// Authenticates the fluent http request using http basic authentication.
 /// </summary>
 /// <param name="fluentHttpRequest">
 /// The fluent http request.
 /// </param>
 public void Authenticate(FluentHttpRequest fluentHttpRequest)
 {
     fluentHttpRequest.Headers(
         headers =>
         headers.Add(
             "Authorization",
             string.Concat("Basic ",
                           Convert.ToBase64String(
                               Encoding.UTF8.GetBytes(string.Format("{0}:{1}", Username, Password))))));
 }
Пример #3
0
        internal static void AttachRequestBodyAndUpdateHeader(FluentHttpRequest request, IDictionary <string, object> parameters, string boundary)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (parameters == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(boundary))
            {
                boundary = DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture);
            }

            var mediaObjects = ExtractMediaObjects(parameters);

            if (mediaObjects.Count == 0)
            {
                request.Headers(h => h.Add("Content-Type", "application/x-www-form-urlencoded"));

                var sb = new StringBuilder();

                bool isFirst = true;
                foreach (var key in parameters.Keys)
                {
                    if (isFirst)
                    {
                        isFirst = false;
                    }
                    else
                    {
                        sb.Append("&");
                    }

                    if (parameters[key] != null)
                    {
                        // Format Object As Json And Remove leading and trailing parenthesis
                        string jsonValue = SimpleJson.SimpleJson.SerializeObject(parameters[key]);
                        jsonValue = SimpleJson.SimpleJson.EscapeToJavascriptString(jsonValue);

                        if (jsonValue.StartsWith("\"", StringComparison.Ordinal))
                        {
                            jsonValue = jsonValue.Substring(1, jsonValue.Length - 1);
                        }

                        if (jsonValue.EndsWith("\"", StringComparison.Ordinal))
                        {
                            jsonValue = jsonValue.Substring(0, jsonValue.Length - 1);
                        }

                        if (!string.IsNullOrEmpty(jsonValue))
                        {
                            sb.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}", FluentHttpRequest.UrlEncode(key), FluentHttpRequest.UrlEncode(jsonValue));
                        }
                    }
                    else
                    {
                        sb.Append(FluentHttpRequest.UrlEncode(key));
                    }

                    request.Body(body => body.Append(sb.ToString()));
                }
            }
            else
            {
                request.Headers(h => h.Add("Content-Type", string.Concat("multipart/form-data; boundary=", boundary)));

                // Build up the post message header
                var sb = new StringBuilder();
                foreach (var kvp in parameters)
                {
                    sb.AppendFormat("{0}{1}{2}", MultiPartFormPrefix, boundary, MultiPartNewLine);
                    sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\"", kvp.Key);
                    sb.AppendFormat("{0}{0}{1}{0}", MultiPartNewLine, kvp.Value);
                }

                request.Body(b => b.Append(sb.ToString()));

                var newLine = Encoding.UTF8.GetBytes(MultiPartNewLine);
                foreach (var kvp in mediaObjects)
                {
                    var sbMediaObject = new StringBuilder();
                    var mediaObject   = kvp.Value;

                    if (mediaObject.ContentType == null || mediaObject.GetValue() == null || string.IsNullOrEmpty(mediaObject.FileName))
                    {
                        throw new InvalidOperationException("The media object must have a content type, file name, and value set.");
                    }

                    sbMediaObject.AppendFormat("{0}{1}{2}", MultiPartFormPrefix, boundary, MultiPartNewLine);
                    sbMediaObject.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", kvp.Key, mediaObject.FileName, MultiPartNewLine);
                    sbMediaObject.AppendFormat("Content-Type: {0}{1}{1}", mediaObject.ContentType, MultiPartNewLine);

                    byte[] fileData = mediaObject.GetValue();
                    Debug.Assert(fileData != null, "The value of MediaObject is null.");

                    request.Body(b => b
                                 .Append(sbMediaObject.ToString())
                                 .Append(fileData)
                                 .Append(newLine));
                }

                request.Body(body => body.Append(Encoding.UTF8.GetBytes(string.Concat(MultiPartNewLine, MultiPartFormPrefix, boundary, MultiPartFormPrefix, MultiPartNewLine))));
            }
        }
Пример #4
0
 /// <summary>
 /// Authenticate the fluent http request using OAuth2 authorization header bearer_token.
 /// </summary>
 /// <param name="fluentHttpRequest">The fluent http request.</param>
 public override void Authenticate(FluentHttpRequest fluentHttpRequest)
 {
     fluentHttpRequest.Headers(h => h.Add("Authorization", string.Concat("Bearer ", BearerToken)));
 }
Пример #5
0
        internal static void AttachRequestBodyAndUpdateHeader(FluentHttpRequest request, IDictionary<string, object> parameters, string boundary)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            if (parameters == null)
                return;

            if (string.IsNullOrEmpty(boundary))
                boundary = DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture);

            var mediaObjects = ExtractMediaObjects(parameters);

            if (mediaObjects.Count == 0)
            {
                request.Headers(h => h.Add("Content-Type", "application/x-www-form-urlencoded"));

                var sb = new StringBuilder();

                bool isFirst = true;
                foreach (var key in parameters.Keys)
                {
                    if (isFirst)
                        isFirst = false;
                    else
                        sb.Append("&");

                    if (parameters[key] != null)
                    {
                        // Format Object As Json And Remove leading and trailing parenthesis
                        string jsonValue = SimpleJson.SimpleJson.SerializeObject(parameters[key]);
                        jsonValue = SimpleJson.SimpleJson.EscapeToJavascriptString(jsonValue);

                        if (jsonValue.StartsWith("\"", StringComparison.Ordinal))
                            jsonValue = jsonValue.Substring(1, jsonValue.Length - 1);

                        if (jsonValue.EndsWith("\"", StringComparison.Ordinal))
                            jsonValue = jsonValue.Substring(0, jsonValue.Length - 1);

                        if (!string.IsNullOrEmpty(jsonValue))
                            sb.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}", FluentHttpRequest.UrlEncode(key), FluentHttpRequest.UrlEncode(jsonValue));
                    }
                    else
                    {
                        sb.Append(FluentHttpRequest.UrlEncode(key));
                    }

                    request.Body(body => body.Append(sb.ToString()));
                }
            }
            else
            {
                request.Headers(h => h.Add("Content-Type", string.Concat("multipart/form-data; boundary=", boundary)));

                // Build up the post message header
                var sb = new StringBuilder();
                foreach (var kvp in parameters)
                {
                    sb.AppendFormat("{0}{1}{2}", MultiPartFormPrefix, boundary, MultiPartNewLine);
                    sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\"", kvp.Key);
                    sb.AppendFormat("{0}{0}{1}{0}", MultiPartNewLine, kvp.Value);
                }

                request.Body(b => b.Append(sb.ToString()));

                var newLine = Encoding.UTF8.GetBytes(MultiPartNewLine);
                foreach (var kvp in mediaObjects)
                {
                    var sbMediaObject = new StringBuilder();
                    var mediaObject = kvp.Value;

                    if (mediaObject.ContentType == null || mediaObject.GetValue() == null || string.IsNullOrEmpty(mediaObject.FileName))
                        throw new InvalidOperationException("The media object must have a content type, file name, and value set.");

                    sbMediaObject.AppendFormat("{0}{1}{2}", MultiPartFormPrefix, boundary, MultiPartNewLine);
                    sbMediaObject.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", kvp.Key, mediaObject.FileName, MultiPartNewLine);
                    sbMediaObject.AppendFormat("Content-Type: {0}{1}{1}", mediaObject.ContentType, MultiPartNewLine);

                    byte[] fileData = mediaObject.GetValue();
                    Debug.Assert(fileData != null, "The value of MediaObject is null.");

                    request.Body(b => b
                                          .Append(sbMediaObject.ToString())
                                          .Append(fileData)
                                          .Append(newLine));
                }

                request.Body(body => body.Append(Encoding.UTF8.GetBytes(string.Concat(MultiPartNewLine, MultiPartFormPrefix, boundary, MultiPartFormPrefix, MultiPartNewLine))));
            }
        }
Пример #6
0
 /// <summary>
 /// Authenticate the fluent http request using OAuth2 authorization header bearer_token.
 /// </summary>
 /// <param name="fluentHttpRequest">The fluent http request.</param>
 public override void Authenticate(FluentHttpRequest fluentHttpRequest)
 {
     fluentHttpRequest.Headers(h => h.Add("Authorization", string.Concat("Bearer ", BearerToken)));
 }
Пример #7
0
        internal virtual FluentHttpRequest PrepareRequest(GithubApiVersion version, string method, string path, object parameters, Stream responseStream)
        {
            var request = new FluentHttpRequest()
                .ResourcePath(path)
                .Method(method)
                .Proxy(Proxy)
                .OnResponseHeadersReceived((o, e) => e.SaveResponseIn(responseStream));

            request.BaseUrl(version == GithubApiVersion.V3
                                ? "https://api.github.com"
                                : "https://github.com/api/v2/json");

            string bearerToken = null;

            IDictionary<string, object> dictionaryParameters = null;
            if (parameters is IDictionary<string, object>)
                dictionaryParameters = (IDictionary<string, object>)parameters;

            // give priority to bearer_token then access_token specified in parameters.
            if (dictionaryParameters != null)
            {
                if (dictionaryParameters.ContainsKey("bearer_token"))
                {
                    bearerToken = dictionaryParameters["bearer_token"].ToString();
                    dictionaryParameters.Remove(bearerToken);
                }
                else if (dictionaryParameters.ContainsKey("access_token"))
                {
                    bearerToken = dictionaryParameters["access_token"].ToString();
                    dictionaryParameters.Remove(bearerToken);
                }
            }

            if (Authentication != null)
            {
                if (string.IsNullOrEmpty(bearerToken) && Authentication is GithubOAuthAuthenticator)
                {
                    var oauth2 = (GithubOAuthAuthenticator)Authentication;
                    bearerToken = oauth2.AccessToken;
                }

                if (string.IsNullOrEmpty(bearerToken))
                {
                    if (Authentication is GithubBasicAuthenticator)
                    {
                        var basicAuth = (GithubBasicAuthenticator)Authentication;
                        request.AuthenticateUsing(new HttpBasicAuthenticator(basicAuth.Username, basicAuth.Password));
                    }
                    else
                    {
                        throw new NotSupportedException("Authentication not supported.");
                    }
                }
                else
                {
                    request.AuthenticateUsing(new OAuth2AuthorizationRequestHeaderBearerAuthenticator(bearerToken));
                }
            }

            if (method.Equals("GET", StringComparison.OrdinalIgnoreCase))
            {
                // for GET, all parameters goes as querystring
                request.QueryStrings(qs => qs.Add(dictionaryParameters));
            }
            else
            {
                return request
                    .Headers(h => h.Add("Content-Type", "application/json"))
                    .Body(b =>
                              {
                                  if (parameters != null)
                                      b.Append(JsonSerializer.Current.SerializeObject(parameters));
                              });
            }

            return request;
        }