protected virtual Dictionary <string, string> headersForRequest(HTTPVerb httpVerb, Dictionary <string, string> headers = null) { headers = headers ?? new Dictionary <string, string>(); switch (httpVerb) { case HTTPVerb.GET: headers.Add("METHOD", "GET"); break; case HTTPVerb.POST: headers.Add("METHOD", "POST"); break; case HTTPVerb.PUT: headers.Add("METHOD", "PUT"); headers.Add("X-HTTP-Method-Override", "PUT"); break; case HTTPVerb.DELETE: headers.Add("METHOD", "DELETE"); headers.Add("X-HTTP-Method-Override", "DELETE"); break; } return(headers); }
public void graphRequest(string path, HTTPVerb verb, Dictionary <string, object> parameters, Action <string, object> completionHandler) { if (this.shouldSendRequest()) { base.surrogateMonobehaviour.StartCoroutine(this.send(path, verb, parameters, completionHandler)); } else { try { Type type = typeof(Facebook).Assembly.GetType("FacebookAndroid"); if (type != null) { MethodInfo method = type.GetMethod("babysitRequest", BindingFlags.Static | BindingFlags.NonPublic); if (method != null) { Action action = delegate { this.surrogateMonobehaviour.StartCoroutine(this.send(path, verb, parameters, completionHandler)); }; method.Invoke(null, new object[] { verb == HTTPVerb.POST, action }); } } } catch (Exception) { } } }
public void graphRequest(string path, HTTPVerb verb, Dictionary <string, object> parameters, Action <string, object> completionHandler) { if (shouldSendRequest()) { surrogateMonobehaviour.StartCoroutine(send(path, verb, parameters, completionHandler)); } else { // if we have an auth helper we will use it because we are not logged in // auth helpers are classes in the FacebookBinding and FacebookAndroid files try { #if UNITY_IPHONE var type = typeof(Facebook).Assembly.GetType("FacebookBinding"); #else var type = typeof(Facebook).Assembly.GetType("FacebookAndroid"); #endif // this will pass for iOS and Android when the SocialNetworking Plugin is present if (type != null) { var method = type.GetMethod("babysitRequest", BindingFlags.Static | BindingFlags.NonPublic); if (method != null) { Action action = () => { surrogateMonobehaviour.StartCoroutine(send(path, verb, parameters, completionHandler)); }; method.Invoke(null, new object[] { verb == HTTPVerb.POST, action }); } } } catch (Exception) {} } }
protected virtual IEnumerator send(string path, HTTPVerb httpVerb, Dictionary <string, object> parameters, Action <string, object> onComplete) { if (path.StartsWith("/")) { path = path.Substring(1); } WWW www = processRequest(path, httpVerb, parameters); yield return(www); if (debugRequests) { Debug.Log("response error: " + www.error); Debug.Log("response text: " + www.text); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("Response Headers:\n"); foreach (KeyValuePair <string, string> responseHeader in www.responseHeaders) { stringBuilder.AppendFormat("{0}: {1}\n", responseHeader.Key, responseHeader.Value); } Debug.Log(stringBuilder.ToString()); } if (onComplete != null) { processResponse(www, onComplete); } www.Dispose(); }
/// <summary> /// Initializes a new instance of the <see cref="WebRequestBuilder"/> class. /// </summary> /// <param name="requestUri">The request URI.</param> /// <param name="verb">The http verb.</param> /// <param name="userAgent">The http user agent.</param> /// <param name="networkCredentials">The network credentials.</param> /// <remarks></remarks> public WebRequestBuilder(Uri requestUri, HTTPVerb verb, String userAgent, NetworkCredential networkCredentials) { if (requestUri == null) { throw new ArgumentNullException("requestUri"); } this.RequestUri = requestUri; this.Verb = verb; this.userAgent = userAgent; this.UseOAuth = false; if (networkCredentials != null) { this.networkCredentials = networkCredentials; } this.Parameters = new Dictionary <string, object>(); if (string.IsNullOrEmpty(this.RequestUri.Query)) { return; } foreach (Match item in Regex.Matches(this.RequestUri.Query, @"(?<key>[^&?=]+)=(?<value>[^&?=]+)")) { this.Parameters.Add(item.Groups["key"].Value, item.Groups["value"].Value); } this.RequestUri = new Uri(this.RequestUri.AbsoluteUri.Replace(this.RequestUri.Query, "")); }
private bool MakeRequest(string targetPoint, HTTPVerb targetAction, out string data) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetPoint); request.Method = targetAction.ToString(); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { try { using (Stream responseStream = response.GetResponseStream()) { if (responseStream != null) { using (StreamReader reader = new StreamReader(responseStream)) { data = reader.ReadToEnd(); } } else { data = ""; return(false); } } } catch { data = ""; return(false); } } return(true); }
public ICoffeeFunction GetFunctionFromRequest(HTTPVerb verb) { var functionDict = GetFunctionDictionary(); return(functionDict.ContainsKey(verb) ? (ICoffeeFunction)Activator.CreateInstance(functionDict[verb]) : null); }
protected async Task <TOut> InvokeMethodAsync <TOut, TBody>(string serviceName, string serviceEndpoint, HTTPVerb type, IDictionary <string, string> queryParameters = null, TBody body = null) where TBody : class { var httpExtension = GenerateExtension(type, queryParameters: queryParameters); return(await DaprClient.InvokeMethodAsync <TBody, TOut>(serviceName, serviceEndpoint, body, httpExtension)); }
/// <summary> /// Initializes a new instance of the <see cref="TwitterCommand<T>"/> class. /// </summary> /// <param name="method">The method.</param> /// <param name="endPoint">The end point.</param> /// <param name="tokens">The tokens.</param> /// <param name="optionalProperties">The optional properties.</param> protected TwitterCommand(HTTPVerb method, string endPoint, OAuthTokens tokens, OptionalProperties optionalProperties) { this.RequestParameters = new Dictionary <string, object>(); this.Verb = method; this.Tokens = tokens; this.OptionalProperties = optionalProperties ?? new OptionalProperties(); this.SetCommandUri(endPoint); }
/// <summary> /// Initializes a new instance of the <see cref="NCDCCommand<T>"/> class. /// </summary> /// <param name="method">The method.</param> /// <param name="endPoint">The end point.</param> /// <param name="token">The token.</param> /// <param name="optionalProperties">The optional properties.</param> /// <remarks></remarks> protected NCDCCommand(HTTPVerb method, string endPoint, string token, NCDCOptions optionalProperties) { this.RequestParameters = new Dictionary <string, object>(); this.Verb = method; this.Token = token; this.NCDCOptions = optionalProperties ?? new NCDCOptions(); NCDCUtilities.CurrentToken = this.Token; this.SetCommandUri(endPoint); }
public static string GetHttpVerbName(HTTPVerb verb) { switch (verb) { default: case HTTPVerb.GET: return(UnityWebRequest.kHttpVerbGET); case HTTPVerb.POST: return(UnityWebRequest.kHttpVerbPOST); } }
protected override IEnumerator send( string path, HTTPVerb httpVerb, Dictionary<string,object> parameters, Action<string, object> onComplete ) { if( parameters == null ) parameters = new Dictionary<string, object>(); // add the access token if we dont have one in the dictionary if( !parameters.ContainsKey( "access_token" ) ) parameters.Add( "access_token", accessToken ); return base.send( path, httpVerb, parameters, onComplete ); }
public NCDCWebRequest(Uri uri, HTTPVerb hTTPVerb, string token, string userAgent = "") { if (uri == null) { throw new ArgumentNullException("requestUri"); } // TODO: Complete member initialization this.RequestUri = uri; this.Verb = hTTPVerb; this.Token = token; this.UserAgent = userAgent; this.Parameters = new Dictionary <string, object>(); }
private async Task <string> GetResourceId(EntryComponent entry, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(entry.Request.IfNoneExist) && !entry.Request.Url.Contains("?", StringComparison.Ordinal)) { if (entry.Request.Method == HTTPVerb.POST) { return(entry.FullUrl); } return(entry.Request.Url); } else { string resourceType = null; StringValues conditionalQueries; HTTPVerb requestMethod = (HTTPVerb)entry.Request.Method; bool conditionalCreate = requestMethod == HTTPVerb.POST; bool condtionalUpdate = requestMethod == HTTPVerb.PUT; if (condtionalUpdate) { string[] conditinalUpdateParameters = entry.Request.Url.Split("?"); resourceType = conditinalUpdateParameters[0]; conditionalQueries = conditinalUpdateParameters[1]; } else if (conditionalCreate) { resourceType = entry.Request.Url; conditionalQueries = entry.Request.IfNoneExist; } IReadOnlyCollection <SearchResultEntry> matchedResults = await _referenceResolver.GetExistingResourceId(entry.Request.Url, resourceType, conditionalQueries, cancellationToken); int?count = matchedResults?.Count; if (count > 1) { // Multiple matches: The server returns a 412 Precondition Failed error indicating the client's criteria were not selective enough throw new PreconditionFailedException(string.Format(Api.Resources.ConditionalOperationInBundleNotSelectiveEnough, conditionalQueries)); } if (count == 1) { return(entry.Resource.TypeName + "/" + matchedResults.First().Resource.ResourceId); } } return(string.Empty); }
protected override IEnumerator send(string path, HTTPVerb httpVerb, Dictionary <string, object> parameters, Action <string, object> onComplete) { if (parameters == null) { parameters = new Dictionary <string, object>(); } // add the access token if we dont have one in the dictionary if (!parameters.ContainsKey("access_token")) { parameters.Add("access_token", accessToken); } return(base.send(path, httpVerb, parameters, onComplete)); }
protected override IEnumerator send(string path, HTTPVerb httpVerb, Dictionary <string, object> parameters, Action <string, object> onComplete) { if (parameters == null) { parameters = new Dictionary <string, object>(); } if (!parameters.ContainsKey("access_token")) { parameters.Add("access_token", this.accessToken); } if (httpVerb == HTTPVerb.PUT || httpVerb == HTTPVerb.DELETE) { parameters.Add("method", httpVerb.ToString()); } return(base.send(path, httpVerb, parameters, onComplete)); }
private HTTPExtension GenerateExtension(HTTPVerb type, IDictionary <string, string> queryParameters = null) { var httpExtension = new HTTPExtension { ContentType = "application/json", Verb = type }; httpExtension.Headers.Add("Authorization", $"Bearer {TokenManager.Token}"); if (queryParameters != null) { httpExtension.QueryString = queryParameters; } return(httpExtension); }
/// <summary> /// Initializes a new instance of the <see cref="WebRequestBuilder"/> class. /// </summary> /// <param name="requestUri">The request URI.</param> /// <param name="verb">The verb.</param> /// <param name="tokens">The tokens.</param> /// <param name="userAgent">The user agent.</param> public WebRequestBuilder(Uri requestUri, HTTPVerb verb, OAuthTokens tokens, string userAgent = "") : this(requestUri, verb, userAgent, null) { this.Tokens = tokens; if (tokens != null) { if (string.IsNullOrEmpty(this.Tokens.ConsumerKey) || string.IsNullOrEmpty(this.Tokens.ConsumerSecret)) { throw new ArgumentException("Consumer key and secret are required for OAuth requests."); } if (string.IsNullOrEmpty(this.Tokens.AccessToken) ^ string.IsNullOrEmpty(this.Tokens.AccessTokenSecret)) { throw new ArgumentException("The access token is invalid. You must specify the key AND secret values."); } this.UseOAuth = true; } }
public void restRequest(string method, HTTPVerb verb, Dictionary <string, object> parameters, Action <string, object> completionHandler) { // ensure we return json if (parameters == null) { parameters = new Dictionary <string, object>(); } if (!parameters.ContainsKey("format")) { parameters.Add("format", "json"); } // we have to rejigger the baseUrl temporarily here var path = "method/" + method; var oldBaseUrl = _baseUrl; _baseUrl = "https://api.facebook.com/"; surrogateMonobehaviour.StartCoroutine(send(path, verb, parameters, completionHandler)); _baseUrl = oldBaseUrl; }
/// <summary> /// Initializes a new instance of the <see cref="WebRequestBuilder"/> class. /// </summary> /// <param name="requestUri">The request URI.</param> /// <param name="verb">The verb.</param> /// <param name="tokens">The tokens.</param> public WebRequestBuilder(Uri requestUri, HTTPVerb verb, OAuthTokens tokens) : this(requestUri, verb, string.Empty, null) { }
/// <summary> /// Initializes a new instance of the <see cref="PagedTimelineCommand"/> class. /// </summary> /// <param name="httpMethod">The HTTP method.</param> /// <param name="endPoint">The end point.</param> /// <param name="tokens">The tokens.</param> /// <param name="optionalProperties">The optional properties.</param> protected PagedTimelineCommand(HTTPVerb httpMethod, string endPoint, OAuthTokens tokens, OptionalProperties optionalProperties) : base(httpMethod, endPoint, tokens, optionalProperties) { }
public EndPointPlugin(string URL, HTTPVerb verb = HTTPVerb.ALL) { Url = URL; Verb = verb; // HTTPVerb.ALL; }
/// <summary> /// Initializes a new instance of the <see cref="WebRequestBuilder"/> class. /// </summary> /// <param name="requestUri">The request URI.</param> /// <param name="verb">The http verb.</param> /// <param name="KeepAlive">if set to <c>true</c> the <see cref="System.Net.HttpWebRequest"/> will be instructed to keep the connection alive.</param> /// <param name="UserAgent">The http user agent.</param> /// <param name="NetworkCredentials">The network credentials.</param> /// <remarks></remarks> public WebRequestBuilder(Uri requestUri, HTTPVerb verb, String UserAgent, NetworkCredential NetworkCredentials) { if (requestUri == null) throw new ArgumentNullException("requestUri"); this.RequestUri = requestUri; this.Verb = verb; this.UserAgent = UserAgent; this.UseOAuth = false; if (NetworkCredentials != null) this.NetworkCredentials = NetworkCredentials; this.Parameters = new Dictionary<string, object>(); if (string.IsNullOrEmpty(this.RequestUri.Query)) return; foreach (Match item in Regex.Matches(this.RequestUri.Query, @"(?<key>[^&?=]+)=(?<value>[^&?=]+)")) { this.Parameters.Add(item.Groups["key"].Value, item.Groups["value"].Value); } object scopeParams = null; if (this.Parameters.TryGetValue("scope", out scopeParams)) { string paramVal = scopeParams as String; if (!string.IsNullOrEmpty(paramVal)) { paramVal = paramVal.Replace("+", " "); this.Parameters["scope"] = (object)paramVal; }//end if }//end if this.RequestUri = new Uri(this.RequestUri.AbsoluteUri.Replace(this.RequestUri.Query, "")); }
/// <summary> /// Prepares the OAuth parameters. /// </summary> /// <param name="baseUrl">The base URL.</param> /// <param name="parameters">The parameters.</param> /// <param name="verb">The verb.</param> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="token">The token.</param> /// <param name="tokenSecret">The token secret.</param> /// <returns> /// /// </returns> private static Dictionary<string, string> PrepareOAuthParameters(string baseUrl, Dictionary<string, string> parameters, HTTPVerb verb, string consumerKey, string consumerSecret, string token, string tokenSecret) { Dictionary<string, string> combinedParameters = new Dictionary<string, string>(); if (parameters != null) { // Copy the given parameters into a new collection, as to not modify the source collection foreach (KeyValuePair<string, string> item in parameters) { combinedParameters.Add(item.Key, item.Value); } } // Add the OAuth parameters combinedParameters.Add("oauth_version", "1.0"); combinedParameters.Add("oauth_nonce", GenerateNonce()); combinedParameters.Add("oauth_timestamp", GenerateTimeStamp()); combinedParameters.Add("oauth_signature_method", "HMAC-SHA1"); combinedParameters.Add("oauth_consumer_key", consumerKey); combinedParameters.Add("oauth_consumer_secret", consumerSecret); if (!string.IsNullOrEmpty(token)) { combinedParameters.Add("oauth_token", token); } if (!string.IsNullOrEmpty(tokenSecret)) { combinedParameters.Add("oauth_token_secret", tokenSecret); } AddSignatureToParameters( new Uri(baseUrl), combinedParameters, verb, consumerSecret, tokenSecret); return combinedParameters; }
public void graphRequest( string path, HTTPVerb verb, Dictionary<string, object> parameters, Action<string, object> completionHandler ) { surrogateMonobehaviour.StartCoroutine( send( path, verb, parameters, completionHandler ) ); }
public RESTClient(string Uri, string content, HTTPVerb verb) { EndPoint = Uri; this.Content = content; HttpMethod = verb; }
/// <summary> /// Generates and adds a signature to parameters. /// </summary> /// <param name="url">The base URL.</param> /// <param name="parameters">The parameters.</param> /// <param name="verb">The HTTP verb to perform.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="tokenSecret">The token secret.</param> private static void AddSignatureToParameters( Uri url, Dictionary<string, string> parameters, HTTPVerb verb, string consumerSecret, string tokenSecret) { string normalizedUrl = NormalizeUrl(url); // Get the oauth parameters from the parameters Dictionary<string, string> baseStringParameters = (from p in parameters where !(p.Key.EndsWith("_secret", StringComparison.OrdinalIgnoreCase) && p.Key.StartsWith("oauth_", StringComparison.OrdinalIgnoreCase) && !p.Key.EndsWith("_verifier", StringComparison.OrdinalIgnoreCase)) select p).ToDictionary(p => p.Key, p => p.Value); string signatureBase = string.Format( CultureInfo.InvariantCulture, "{0}&{1}&{2}", verb.ToString().ToUpper(CultureInfo.InvariantCulture), EncodeForUrl(normalizedUrl), UrlEncode(baseStringParameters)); HMACSHA1 hmacsha1 = new HMACSHA1(); string key = string.Format( CultureInfo.InvariantCulture, "{0}&{1}", EncodeForUrl(consumerSecret), EncodeForUrl(tokenSecret)); hmacsha1.Key = Encoding.ASCII.GetBytes(key); string result = Convert.ToBase64String( hmacsha1.ComputeHash( Encoding.ASCII.GetBytes(signatureBase))); // Add the signature to the oauth parameters parameters.Add("oauth_signature", result); #if DEBUG System.Diagnostics.Debug.WriteLine("----------- OAUTH SIGNATURE GENERATION -----------"); System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "url.PathAndQuery = \"{0}\"", url.PathAndQuery)); System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "httpMethod = \"{0}\"", verb.ToString())); System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "consumerSecret = \"{0}\"", consumerSecret)); System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "tokenSecret = \"{0}\"", tokenSecret)); System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "normalizedUrl = \"{0}\"", normalizedUrl)); System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "signatureBase = \"{0}\"", signatureBase)); System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "key = \"{0}\"", key)); System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "signature = \"{0}\"", result)); System.Diagnostics.Debug.WriteLine("--------- END OAUTH SIGNATURE GENERATION ----------"); #endif }
// #if !LITE && !SILVERLIGHT // /// <summary> // /// Gets the access token during callback. // /// </summary> // /// <param name="consumerKey">The consumer key.</param> // /// <param name="consumerSecret">The consumer secret.</param> // /// <returns> // /// Access tokens returned by the Twitter API // /// </returns> // public static OAuthTokenResponse GetAccessTokenDuringCallback(string consumerKey, string consumerSecret) // { // // HttpContext context = HttpContext.Current; // if (context == null || context.Request == null) // { // throw new ApplicationException("Could not located the HTTP context. GetAccessTokenDuringCallback can only be used in ASP.NET applications."); // } // // string requestToken = context.Request.QueryString["oauth_token"]; // string verifier = context.Request.QueryString["oauth_verifier"]; // // if (string.IsNullOrEmpty(requestToken)) // { // throw new ApplicationException("Could not locate the request token."); // } // // if (string.IsNullOrEmpty(verifier)) // { // throw new ApplicationException("Could not locate the verifier value."); // } // // return GetAccessToken(consumerKey, consumerSecret, requestToken, verifier); // } // // /// <summary> // /// Adds the OAuth Echo header to the supplied web request. // /// </summary> // /// <param name="request">The request.</param> // /// <param name="tokens">The tokens.</param> // public static void AddOAuthEchoHeader(WebRequest request, OAuthTokens tokens) // { // WebRequestBuilder builder = new WebRequestBuilder( // new Uri("https://api.twitter.com/1/account/verify_credentials.json"), // HTTPVerb.POST, // tokens, // ""); // // builder.PrepareRequest(); // // request.Headers.Add("X-Verify-Credentials-Authorization", builder.GenerateAuthorizationHeader()); // request.Headers.Add("X-Auth-Service-Provider", "https://api.twitter.com/1/account/verify_credentials.json"); // } //#endif #endregion Other #if !SILVERLIGHT public static OAuthTokenResponse GetRequestToken(string consumerKey, string consumerSecret, string callbackAddress, WebProxy proxy, string requestTokenUrl, HTTPVerb httpVerb) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(callbackAddress)) { throw new ArgumentNullException("callbackAddress", @"You must always provide a callback url when obtaining a request token. For PIN-based authentication, use ""oob"" as the callback url."); } WebRequestBuilder builder = new WebRequestBuilder( new Uri(requestTokenUrl), httpVerb, new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }, "") { Proxy = proxy }; if (!string.IsNullOrEmpty(callbackAddress)) { builder.Parameters.Add("oauth_callback", callbackAddress); } string responseBody = null; try { HttpWebResponse webResponse = builder.ExecuteRequest(); Stream responseStream = webResponse.GetResponseStream(); if (responseStream != null) responseBody = new StreamReader(responseStream).ReadToEnd(); } catch (WebException wex) { throw new Exception(wex.Message, wex); } Match matchedValues = Regex.Match(responseBody, @"oauth_token=(?<token>[^&]+)|oauth_token_secret=(?<secret>[^&]+)|oauth_verifier=(?<verifier>[^&]+)"); return new OAuthTokenResponse { Token = matchedValues.Groups["token"].Value, TokenSecret = matchedValues.Groups["secret"].Value, VerificationString = matchedValues.Groups["verifier"].Value }; }
public void graphRequest(string path, HTTPVerb verb, Dictionary <string, object> parameters, Action <string, object> completionHandler) { surrogateMonobehaviour.StartCoroutine(send(path, verb, parameters, completionHandler)); }
public void graphRequest( string path, HTTPVerb verb, Action<string, object> completionHandler ) { graphRequest( path, verb, null, completionHandler ); }
protected virtual WWW processRequest(string path, HTTPVerb httpVerb, Dictionary <string, object> parameters) { StringBuilder stringBuilder = new StringBuilder(); if (!path.StartsWith("http")) { stringBuilder.Append(_baseUrl).Append(path); } else { stringBuilder.Append(path); } bool flag = httpVerb != HTTPVerb.GET; WWWForm wWWForm = ((!flag) ? null : new WWWForm()); if (parameters != null && parameters.Count > 0) { if (flag) { foreach (KeyValuePair <string, object> parameter in parameters) { if (parameter.Value is string) { wWWForm.AddField(parameter.Key, parameter.Value as string); } else if (parameter.Value is byte[]) { wWWForm.AddBinaryData(parameter.Key, parameter.Value as byte[]); } } } else { bool flag2 = true; if (path.Contains("?")) { flag2 = false; } foreach (KeyValuePair <string, object> parameter2 in parameters) { if (parameter2.Value is string) { stringBuilder.AppendFormat("{0}{1}={2}", (!flag2) ? "&" : "?", WWW.EscapeURL(parameter2.Key), WWW.EscapeURL(parameter2.Value as string)); flag2 = false; } } } } if (debugRequests) { Debug.Log("url: " + stringBuilder.ToString()); } Dictionary <string, string> dictionary = null; if (flag) { IDictionary headersFromForm = getHeadersFromForm(wWWForm); if (headersFromForm != null) { dictionary = new Dictionary <string, string>(); if (headersFromForm.Contains("Content-Type")) { dictionary.Add("Content-Type", headersFromForm["Content-Type"].ToString()); } if (debugRequests) { Debug.Log("Found a POST request. Fetching headers from WWWForm and starting with these as a base: "); Utils.logObject(dictionary); } } } return((!flag) ? new WWW(stringBuilder.ToString()) : new WWW(stringBuilder.ToString(), wWWForm.data, headersForRequest(httpVerb, dictionary))); }
/// <summary> /// Initializes a new instance of the <see cref="WebRequestBuilder"/> class. /// </summary> /// <param name="requestUri">The request URI.</param> /// <param name="verb">The http verb.</param> /// <param name="userAgent">The http user agent.</param> /// <param name="networkCredentials">The network credentials.</param> /// <remarks></remarks> public WebRequestBuilder(Uri requestUri, HTTPVerb verb, String userAgent, NetworkCredential networkCredentials) { if (requestUri == null) throw new ArgumentNullException("requestUri"); this.RequestUri = requestUri; this.Verb = verb; this.userAgent = userAgent; this.UseOAuth = false; if (networkCredentials != null) this.networkCredentials = networkCredentials; this.Parameters = new Dictionary<string, object>(); if (string.IsNullOrEmpty(this.RequestUri.Query)) return; foreach (Match item in Regex.Matches(this.RequestUri.Query, @"(?<key>[^&?=]+)=(?<value>[^&?=]+)")) { this.Parameters.Add(item.Groups["key"].Value, item.Groups["value"].Value); } this.RequestUri = new Uri(this.RequestUri.AbsoluteUri.Replace(this.RequestUri.Query, "")); }
/// <summary> /// /// </summary> /// <returns></returns> protected override TwitterResponse<string> BeginRequest(HTTPVerb overrideVerb = HTTPVerb.GET) { return this.ExecuteRequest(overrideVerb); }
public async Task GivenABundleWithMultipleCalls_WhenProcessed_ThenANotificationWillBeEmitted(BundleType type, HTTPVerb method1, HTTPVerb method2, int code200s, int code404s) { var bundle = new Hl7.Fhir.Model.Bundle { Type = type, Entry = new List <EntryComponent> { new EntryComponent { Request = new RequestComponent { Method = method1, Url = "unused1", }, Resource = new Patient(), }, new EntryComponent { Request = new RequestComponent { Method = method2, Url = "unused2", }, Resource = new Patient(), }, }, }; _router.When(r => r.RouteAsync(Arg.Any <RouteContext>())) .Do(RouteAsyncFunction); BundleMetricsNotification notification = null; await _mediator.Publish(Arg.Do <BundleMetricsNotification>(note => notification = note), Arg.Any <CancellationToken>()); var bundleRequest = new BundleRequest(bundle.ToResourceElement()); BundleResponse bundleResponse = await _bundleHandler.Handle(bundleRequest, default); var bundleResource = bundleResponse.Bundle.ToPoco <Hl7.Fhir.Model.Bundle>(); Assert.Equal(type == BundleType.Batch ? BundleType.BatchResponse : BundleType.TransactionResponse, bundleResource.Type); Assert.Equal(2, bundleResource.Entry.Count); await _mediator.Received().Publish(Arg.Any <BundleMetricsNotification>(), Arg.Any <CancellationToken>()); Assert.Equal(type == BundleType.Batch ? AuditEventSubType.Batch : AuditEventSubType.Transaction, notification.FhirOperation); var results = notification.ApiCallResults; Assert.Equal(code200s, results["200"]); if (code404s > 0) { Assert.Equal(code404s, results["404"]); } else { Assert.Equal(1, results.Keys.Count); } }
public static OAuthTokenResponse GetAccessToken(string consumerKey, string consumerSecret, string requestToken, string accessTokenSecret, string verifier, string accessTokenUrl, HTTPVerb httpVerb, ServiceType serviceType) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(requestToken)) { throw new ArgumentNullException("requestToken"); } WebRequestBuilder builder = new WebRequestBuilder( new Uri(accessTokenUrl), httpVerb, //new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }, new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, AccessToken = requestToken, AccessTokenSecret = accessTokenSecret }, ""); if (!string.IsNullOrEmpty(verifier)) { builder.Parameters.Add("oauth_verifier", verifier); } builder.Parameters.Add("oauth_token", requestToken); string responseBody; try { HttpWebResponse webResponse = builder.ExecuteRequest(); responseBody = new StreamReader(webResponse.GetResponseStream()).ReadToEnd(); } catch (WebException wex) { throw new Exception(wex.Message, wex); } OAuthTokenResponse response = new OAuthTokenResponse(); response.Token = Regex.Match(responseBody, @"oauth_token=([^&]+)").Groups[1].Value; response.TokenSecret = Regex.Match(responseBody, @"oauth_token_secret=([^&]+)").Groups[1].Value; if (serviceType == ServiceType.Twitter) { response.UserId = long.Parse(Regex.Match(responseBody, @"user_id=([^&]+)").Groups[1].Value, CultureInfo.CurrentCulture); response.ScreenName = Regex.Match(responseBody, @"screen_name=([^&]+)").Groups[1].Value; } else if (serviceType == ServiceType.DropBox) { response.UserId = long.Parse(Regex.Match(responseBody, @"uid=([^&]+)").Groups[1].Value, CultureInfo.CurrentCulture); }//end if return response; }
/// <summary> /// Creates and executes an OAuth signed HTTP request. /// </summary> /// <param name="baseUrl">The base URL.</param> /// <param name="parameters">The parameters.</param> /// <param name="verb">The HTTP verb to perform.</param> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="token">The access or request token.</param> /// <param name="tokenSecret">The token secret.</param> /// <returns> /// A new instance of the <see cref="System.Net.HttpWebRequest"/> class. /// </returns> internal static HttpWebResponse ExecuteRequest( string baseUrl, Dictionary<string, string> parameters, HTTPVerb verb, string consumerKey, string consumerSecret, string token, string tokenSecret, WebProxy proxy) { Dictionary<string, string> combinedParameters = PrepareOAuthParameters( baseUrl, parameters, verb, consumerKey, consumerSecret, token, tokenSecret); HttpWebResponse response; if (verb == HTTPVerb.POST) { baseUrl = AppendParametersForPOST(baseUrl, combinedParameters); } else { string querystring = GenerateGetQueryString(combinedParameters); if (!string.IsNullOrEmpty(querystring)) { baseUrl = string.Concat(baseUrl, "?", querystring); } } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseUrl); request.Method = verb.ToString(); request.UserAgent = string.Format(CultureInfo.InvariantCulture, "Twitterizer"); request.Headers.Add("Authorization", GenerateAuthorizationHeader(combinedParameters)); if (proxy != null) request.Proxy = proxy; if (verb == HTTPVerb.POST) { request.ContentType = "application/x-www-form-urlencoded"; } #if DEBUG Console.WriteLine("----- Headers -----"); foreach (string key in request.Headers.AllKeys) { Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0} = {1}\n", key, request.Headers[key])); } Console.WriteLine("----- End Of Headers -----"); #endif response = (HttpWebResponse)request.GetResponse(); return response; }
public void ProcessRequest(HttpContext context) { StringBuilder log = new StringBuilder(); string screenName = ""; try { string query = ""; UriBuilder urlBuilder = new UriBuilder("https://api.twitter.com/" + context.Server.UrlDecode(context.Request.QueryString["query"])); // Adds query strings to the url. // some headers may not be copied because they can't be used with clients other than twitter foreach (var queryString in context.Request.QueryString.AllKeys) { switch (queryString) { case "u": case "p": case "query": case "earned": case "pc": break; default: query += string.Format("&{0}={1}", queryString, context.Request.QueryString[queryString]); break; } } if (query.Length > 1) { query = query.Substring(1); } urlBuilder.Query = query; log.AppendLine(query); log.AppendLine("URL: " + urlBuilder.Uri.ToString()); OAuthTokens tokens = new OAuthTokens(); tokens.ConsumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"]; tokens.ConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"]; JToken accessToken; String userFileName = context.Server.MapPath("/App_Data/Users/" + context.Request.QueryString["u"] + "." + context.Request.QueryString["p"]); if (File.Exists(userFileName)) { using (StreamReader str = new StreamReader(userFileName)) { accessToken = JObject.Parse(str.ReadToEnd()); ; } tokens.AccessToken = (string)accessToken.SelectToken("AccessToken"); tokens.AccessTokenSecret = (string)accessToken.SelectToken("AccessSecret"); screenName = (string)accessToken.SelectToken("ScreenName"); log.AppendLine("User FOUND!"); } else { log.AppendLine("User NOT FOUND"); context.Response.StatusCode = 404; return; } //check if the request is xAuth, if it is, simulates the xAuth result for fooling Twitter for iPhone. if (context.Request.QueryString["query"].Contains("oauth/access_token")) { string xAuthResponse = string.Format("oauth_token={0}&oauth_token_secret={1}&user_id={2}&screen_name={3}&x_auth_expires=0", (string)accessToken.SelectToken("AccessToken"), (string)accessToken.SelectToken("AccessSecret"), (string)accessToken.SelectToken("UserId"), (string)accessToken.SelectToken("ScreenName")); context.Response.Write(xAuthResponse); screenName = (string)accessToken.SelectToken("ScreenName"); return; } HTTPVerb verb = HTTPVerb.GET; switch (context.Request.HttpMethod) { case "GET": verb = HTTPVerb.GET; break; case "POST": verb = HTTPVerb.POST; break; case "DELETE": verb = HTTPVerb.DELETE; break; } if (context.Request.Headers["Authorization"] == null) { tokens = null; log.AppendLine("Request NOT authenticated"); } WebRequestBuilder webreq = new WebRequestBuilder(urlBuilder.Uri, verb, tokens); webreq.Multipart = (context.Request.ContentType.Contains("multipart")); if (verb != HTTPVerb.GET) { // adds body parameters to request foreach (var key in context.Request.Form.AllKeys) { webreq.Parameters.Add(key, context.Request.Form[key]); } foreach (var fileKey in context.Request.Files.AllKeys) { webreq.Parameters.Add(fileKey, context.Request.Form[fileKey]); } } ServicePointManager.Expect100Continue = false; HttpWebRequest req = webreq.PrepareRequest(); try { HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); log.AppendLine("get Response"); StreamReader strReader = new StreamReader(resp.GetResponseStream()); String response = strReader.ReadToEnd(); if (ConfigurationManager.AppSettings["debugMode"] == "true") { log.AppendLine(response); } // replaces images url to use TwiX to load them response = Regex.Replace(response, @"(((http:\\/\\/www)|(http:\\/\\/)|(https:\\/\\/www)|(https:\\/\\/)|(www))[-a-zA-Z0-9@:%_\\\+.~#?&//=]+)\.(jpg|jpeg|gif|png|bmp|tiff|tga|svg)", delegate(Match match) { string v = match.ToString(); return(ConfigurationManager.AppSettings["baseUrl"] + "image/" + shFunctions.encryptBase64Url(DES.Encrypt(v.Replace(@"\/", "/").Replace("_normal", ""), shFunctions.key) + ".jpg")); }); strReader.Close(); context.Response.ClearContent(); context.Response.Write(response); } catch (WebException webex) { if (webex.Status == WebExceptionStatus.ProtocolError) { context.Response.StatusCode = (int)((HttpWebResponse)webex.Response).StatusCode; } log.AppendLine("ERROR: " + webex.Message); return; } } catch (Exception ee) { log.AppendLine("Error: " + ee.Message); log.AppendLine("stack: " + ee.StackTrace); } if (ConfigurationManager.AppSettings["log"] == "true") { writeLogToFile(log.ToString(), screenName, context.Request.HttpMethod, context); } //throw new Exception(context.Request.QueryString.ToString()); }
public void graphRequest(string path, HTTPVerb verb, Action <string, object> completionHandler) { graphRequest(path, verb, null, completionHandler); }
/// <summary> /// Prepares the request. It is not nessisary to call this method unless additional configuration is required. /// </summary> /// <returns>A <see cref="HttpWebRequest"/> object fully configured and ready for execution.</returns> public HttpWebRequest PrepareRequest() { SetupOAuth(); formData = null; string contentType = string.Empty; if (!Multipart) { //We don't add the parameters to the query if we are multipart-ing AddQueryStringParametersToUri(); } else { string dataBoundary = "--------------------r4nd0m"; contentType = "multipart/form-data; boundary=" + dataBoundary; formData = GetMultipartFormData(Parameters, dataBoundary); this.Verb = HTTPVerb.POST; } HttpWebRequest request; request = (HttpWebRequest)WebRequest.Create(this.RequestUri); if (this.UseCompression == true) request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; else request.AutomaticDecompression = DecompressionMethods.None; if (this.Proxy != null) request.Proxy = Proxy; if (!this.UseOAuth && this.networkCredentials != null) { request.Credentials = this.networkCredentials; request.UseDefaultCredentials = false; } else { request.UseDefaultCredentials = true; } request.Method = this.Verb.ToString(); request.ContentLength = Multipart ? ((formData != null) ? formData.Length : 0) : 0; request.UserAgent = (string.IsNullOrEmpty(userAgent)) ? string.Format(CultureInfo.InvariantCulture, "EasyTwitter/{0}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version) : userAgent; request.ServicePoint.Expect100Continue = false; if (this.UseOAuth) { request.Headers.Add("Authorization", GenerateAuthorizationHeader()); } if (Multipart) { //Parameters are not added to the query string, post them in the request body instead request.ContentType = contentType; using (Stream requestStream = request.GetRequestStream()) { if (formData != null) { requestStream.Write(formData, 0, formData.Length); } } } return request; }
/// <summary> /// Gets the request token. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="callbackAddress">The callback address. For PIN-based authentication "oob" should be supplied.</param> /// <returns></returns> public static OAuthTokenResponse GetRequestToken(string consumerKey, string consumerSecret, string callbackAddress, string requestTokenUrl, HTTPVerb httpVerb) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(callbackAddress)) { throw new ArgumentNullException("callbackAddress", @"You must always provide a callback url when obtaining a request token. For PIN-based authentication, use ""oob"" as the callback url."); } WebRequestBuilder builder = new WebRequestBuilder( new Uri(requestTokenUrl), httpVerb, new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }, ""); if (!string.IsNullOrEmpty(callbackAddress)) { builder.Parameters.Add("oauth_callback", callbackAddress); } string responseBody = null; try { HttpWebResponse webResponse = builder.ExecuteRequest(); Stream responseStream = webResponse.GetResponseStream(); if (responseStream != null) responseBody = new StreamReader(responseStream).ReadToEnd(); } catch (WebException wex) { throw new Exception(wex.Message, wex); } return new OAuthTokenResponse { Token = ParseQuerystringParameter("oauth_token", responseBody), TokenSecret = ParseQuerystringParameter("oauth_token_secret", responseBody), VerificationString = ParseQuerystringParameter("oauth_verifier", responseBody) }; }
/// <summary> /// /// </summary> /// <param name="overrideVerb"></param> /// <returns></returns> protected abstract TwitterResponse<string> BeginRequest(HTTPVerb overrideVerb = HTTPVerb.GET);
public void graphRequest( string path, HTTPVerb verb, Dictionary<string, object> parameters, Action<string, object> completionHandler ) { // in the editor, we allow requests to be sent as long as we have an access token #if UNITY_EDITOR if( ( accessToken != null && accessToken.Length > 0 ) || shouldSendRequest() ) #else if( shouldSendRequest() ) #endif { surrogateMonobehaviour.StartCoroutine( send( path, verb, parameters, completionHandler ) ); } else { // if we have an auth helper we will use it because we are not logged in // auth helpers are classes in the FacebookBinding and FacebookAndroid files try { #if UNITY_IPHONE var type = typeof( Facebook ).Assembly.GetType( "FacebookBinding" ); #elif UNITY_ANDROID var type = typeof( Facebook ).Assembly.GetType( "FacebookAndroid" ); #endif #if UNITY_IPHONE || UNITY_ANDROID // this will pass for iOS and Android when the SocialNetworking Plugin is present if( type != null ) { var method = type.GetMethod( "babysitRequest", BindingFlags.Static | BindingFlags.NonPublic ); if( method != null ) { Action action = () => { surrogateMonobehaviour.StartCoroutine( send( path, verb, parameters, completionHandler ) ); }; method.Invoke( null, new object[] { verb == HTTPVerb.POST, action } ); } } #endif } catch( Exception ) {} } }
/// <summary> /// /// </summary> /// <param name="overrideVerb"></param> /// <returns></returns> protected virtual TwitterResponse<string> ExecuteRequest(HTTPVerb overrideVerb) { this.Verb = overrideVerb; if (String.IsNullOrEmpty(this.Method)) throw new ArgumentNullException("Method"); WebRequestBuilder builder = new WebRequestBuilder( new Uri(this.BaseUri + this.Method), this.Verb, this.Tokens); string responseBody = String.Empty; try { if (this.AdditionalParameters.Count > 0) { foreach (var item in this.AdditionalParameters) builder.Parameters.Add(item.Key, item.Value); if(this.Verb==HTTPVerb.POST) builder.Multipart = true; } HttpWebResponse webResponse = builder.ExecuteRequest(); Stream responseStream = webResponse.GetResponseStream(); if (responseStream != null) responseBody = new StreamReader(responseStream).ReadToEnd(); } catch (WebException wex) { TwitterStatus status = TwitterStatus.GeneralError; ; if (wex.Status == WebExceptionStatus.ProtocolError) { switch(((HttpWebResponse)wex.Response).StatusCode) { case HttpStatusCode.BadRequest: status = TwitterStatus.BadRequest; break; case HttpStatusCode.Unauthorized: status = TwitterStatus.Unauthorized; break; case HttpStatusCode.NotFound: status = TwitterStatus.FileNotFound; break; case HttpStatusCode.NotAcceptable: status = TwitterStatus.NotAcceptable; break; default: status = TwitterStatus.GeneralError; break; } } return new TwitterResponse<string>() { Status = status, ObjectResponse = String.Empty }; } return new TwitterResponse<string>() { Status = TwitterStatus.Success, ObjectResponse = responseBody }; }
public Endpoint(string URL, HTTPVerb verb = HTTPVerb.ALL) { Url = URL; Type = ContentType.HTML; Verb = verb; // HTTPVerb.ALL; }
public void restRequest( string method, HTTPVerb verb, Dictionary<string, object> parameters, Action<string, object> completionHandler ) { // ensure we return json if( parameters == null ) parameters = new Dictionary<string,object>(); if( !parameters.ContainsKey( "format" ) ) parameters.Add( "format", "json" ); // we have to rejigger the baseUrl temporarily here var path = "method/" + method; var oldBaseUrl = _baseUrl; _baseUrl = "https://api.facebook.com/"; surrogateMonobehaviour.StartCoroutine( send( path, verb, parameters, completionHandler ) ); _baseUrl = oldBaseUrl; }