public static void SendData(HTTPRequestMethod method, string url, bool haveAuth = true, UnityAction <UnityWebRequest> callback = null, List <KeyValuePair <string, string> > headers = default, string body = "") { if (headers == null) { headers = new List <KeyValuePair <string, string> >(); } if (haveAuth && !string.IsNullOrEmpty(JWTTokenService.AccessToken)) { List <KeyValuePair <string, string> > headersLst = new List <KeyValuePair <string, string> >(); headersLst.AddRange(headers); headersLst.Add(new KeyValuePair <string, string>("Authorization", JWTTokenService.AccessToken)); HTTPService.SendData(method, url, request => { // Refresh Token if (request.responseCode == (int)ResponseCodes.UNAUTHORIZED_401 && !string.IsNullOrEmpty(JWTTokenService.RefreshToken)) { headersLst.Add(new KeyValuePair <string, string>("Authorization", JWTTokenService.AccessToken)); HTTPService.SendData(method, url, callback, headersLst.ToArray(), body); } else { callback(request); } }, headersLst.ToArray(), body); } else { HTTPService.SendData(method, url, callback, headers.ToArray(), body); } }
/// <summary> /// Tries to send a request m_NumberOfAttempts of times /// </summary> private HttpWebResponse TrySend(HTTPRequestMethod method, string contentType, Uri uri, Stream body = null) { for (var n = 0; n < m_Attempts; ++n) { try { var req = CreateRequest(method, contentType, uri, body); return(SendRequest(req)); } catch (System.Net.WebException ex) { var retry = CanRetryRequest(ex); if (!retry) { throw new FileSystemException(ex.Message, ex); } var rnd = new Random(); Thread.Sleep((1 << n) * 1000 + rnd.Next(1001)); } } return(null); }
private static IEnumerator SendDataCoroutine(HTTPRequestMethod method, string url, UnityAction <UnityWebRequest> callback, KeyValuePair <string, string>[] headers, string body) { UnityWebRequest request = new UnityWebRequest(); request.method = method.ToString(); request.url = url; // Add Body if (!string.IsNullOrEmpty(body)) { byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(body); request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw); } request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); // Add Headers request.SetRequestHeader("Content-Type", "application/json"); if (headers != default) { foreach (var item in headers) { request.SetRequestHeader(item.Key, item.Value); } } yield return(request.SendWebRequest()); callback?.Invoke(request); }
public void SenTo(String uri, HTTPRequestMethod httpMethod, List <KeyValuePair <string, string> > postData) { HttpClient httpClient = new HttpClient(); // httpClient.BaseAddress = new Uri("http://localhost:8080"); //httpClient.DefaultRequestHeaders.Add("User-Agent", "Indexification URL Adder 1.0"); switch (httpMethod) { case HTTPRequestMethod.HTTPRequestMethod_Get: httpClient.GetAsync(uri) .ContinueWith(postTask => { if (RequestCompleted != null) { RequestCompleted(GetResponseObject(postTask)); } }); break; case HTTPRequestMethod.HTTPRequestMethod_Post: HttpContent content = new FormUrlEncodedContent(postData); httpClient.PostAsync(uri, content) .ContinueWith(postTask => { if (RequestCompleted != null) { RequestCompleted(GetResponseObject(postTask)); } }); break; } }
public static JSONDynamicObject GetJsonAsDynamic(string uri, IWebClientCaller caller, HTTPRequestMethod method = HTTPRequestMethod.GET, IDictionary <string, string> queryParameters = null, IDictionary <string, string> bodyParameters = null, IDictionary <string, string> headers = null) { return(GetJsonAsDynamic(new Uri(uri), caller, method, queryParameters, bodyParameters, headers)); }
public static XDocument GetXML(string uri, IWebClientCaller caller, HTTPRequestMethod method = HTTPRequestMethod.GET, IDictionary <string, string> queryParameters = null, IDictionary <string, string> bodyParameters = null, IDictionary <string, string> headers = null) { return(GetXML(new Uri(uri), caller, method, queryParameters, bodyParameters, headers)); }
public static JSONDataMap GetValueMap(string uri, IWebClientCaller caller, HTTPRequestMethod method = HTTPRequestMethod.GET, IDictionary <string, string> queryParameters = null, IDictionary <string, string> bodyParameters = null, IDictionary <string, string> headers = null) { return(GetValueMap(new Uri(uri), caller, method, queryParameters, bodyParameters, headers)); }
static void Main(string[] args) { if (args.Length == 4) { string hostname = args[0]; int port = int.Parse(args[1]); HTTPRequestMethod command = (HTTPRequestMethod)Enum.Parse(typeof(HTTPRequestMethod), args[2].ToUpper()); string filename = args[3]; IPAddress[] ipv4Addresses = Array.FindAll(Dns.GetHostEntry(hostname).AddressList, a => a.AddressFamily == AddressFamily.InterNetwork); filename = filename.Replace('\\', '/'); using (Socket client = new Socket(SocketType.Stream, ProtocolType.Tcp)) { HTTPRequest req = new HTTPRequest(); req.Header.ProtocolVersion = "HTTP/1.1"; req.Header.ResourceLocation = filename; bool isValid = false; if (command == HTTPRequestMethod.GET) { req.Header.Method = HTTPRequestMethod.GET; isValid = true; } else if (command == HTTPRequestMethod.PUT) { req.Header.Method = HTTPRequestMethod.PUT; if (File.Exists(filename) == true) { using (FileStream fs = new FileStream(filename, FileMode.Open)) { using (BinaryReader bw = new BinaryReader(fs)) { req.RawBody = bw.ReadBytes((int)fs.Length); } } isValid = true; } } if (isValid == true) { client.Connect(new IPEndPoint(ipv4Addresses[0], port)); client.Send(req.GetResponseStream()); Console.WriteLine(ASCIIEncoding.GetEncoding(0).GetString(ReadResponse(client))); } } } else { Console.WriteLine("YetAnotherWebServer hostname port command filename"); } }
public static JSONDataMap GetJson(Uri uri, IWebClientCaller caller, HTTPRequestMethod method = HTTPRequestMethod.GET, IDictionary <string, string> queryParameters = null, IDictionary <string, string> bodyParameters = null, IDictionary <string, string> headers = null) { string responseStr = GetString(uri, caller, method, queryParameters: queryParameters, bodyParameters: bodyParameters, headers: headers); return(string.IsNullOrWhiteSpace(responseStr) ? null : responseStr.JSONToDataObject() as JSONDataMap); }
public static string AddMethodAndBaseURL(string headerStr, HTTPRequestMethod method, string baseURL) { StringBuilder b = new StringBuilder(); b.Append(method.ToString()); b.Append('&'); b.Append(RFC3986.Encode(baseURL)); b.Append('&'); b.Append(RFC3986.Encode(headerStr)); return(b.ToString()); }
public static string AddMethodAndBaseURL(string headerStr, HTTPRequestMethod method, string baseURL) { StringBuilder b = new StringBuilder(); b.Append(method.ToString()); b.Append('&'); b.Append(RFC3986.Encode(baseURL)); b.Append('&'); b.Append(RFC3986.Encode(headerStr)); return b.ToString(); }
public static XDocument GetXML(Uri uri, IWebClientCaller caller, HTTPRequestMethod method = HTTPRequestMethod.GET, IDictionary <string, string> queryParameters = null, IDictionary <string, string> bodyParameters = null, IDictionary <string, string> headers = null) { string responseStr = GetString(uri, caller, method, queryParameters: queryParameters, bodyParameters: bodyParameters, headers: headers); return(string.IsNullOrWhiteSpace(responseStr) ? null : XDocument.Parse(responseStr)); }
private dynamic Send(HTTPRequestMethod method, string contentType, Uri uri, Stream body = null) { if (m_AccessToken.IsNullOrEmpty()) { RefreshAccessToken(); } var res = TrySend(method, contentType, uri, body); return(res.GetJSON()); }
public static JSONDataMap GetValueMap(Uri uri, IWebClientCaller caller, HTTPRequestMethod method = HTTPRequestMethod.GET, IDictionary <string, string> queryParameters = null, IDictionary <string, string> bodyParameters = null, IDictionary <string, string> headers = null) { string responseStr = GetString(uri, caller, method, queryParameters: queryParameters, bodyParameters: bodyParameters, headers: headers); var dict = JSONDataMap.FromURLEncodedString(responseStr); return(dict); }
public static string GetString(Uri uri, IWebClientCaller caller, HTTPRequestMethod method = HTTPRequestMethod.GET, IDictionary <string, string> queryParameters = null, IDictionary <string, string> bodyParameters = null, string body = null, IDictionary <string, string> headers = null) { RequestParams request = new RequestParams() { Uri = uri, Caller = caller, Method = method, QueryParameters = queryParameters, BodyParameters = bodyParameters, Body = body, Headers = headers }; return(GetString(request)); }
private HttpWebRequest CreateRequest(HTTPRequestMethod method, string contentType, Uri uri, Stream body = null) { var fullUri = new Uri(ApiUrls.GoogleApi(), uri); var req = WebRequest.CreateHttp(fullUri); req.Method = method.ToString(); if (m_Timeout > 0) { req.Timeout = m_Timeout; } req.Headers.Add(HEADER_AUTHORIZATION, "Bearer " + m_AccessToken); req.UserAgent = USER_AGENT; var canHaveBody = method == HTTPRequestMethod.PUT || method == HTTPRequestMethod.POST || method == HTTPRequestMethod.PATCH; if (canHaveBody && body != null) { req.ContentType = contentType; req.ContentLength = body.Length; using (var stream = req.GetRequestStream()) { body.Position = 0; body.CopyTo(stream); stream.Flush(); stream.Close(); } } return(req); }
private JSONDynamicObject getResponse(BraintreeSession session, Uri uri, HTTPRequestMethod method, object body) { if (!session.IsValid) { throw new PaymentException("Braintree: " + StringConsts.PAYMENT_BRAINTREE_SESSION_INVALID.Args(this.GetType().Name + ".getResponse")); } var prms = new WebClient.RequestParams() { Caller = this, Uri = uri, Method = HTTPRequestMethod.POST, AcceptType = ContentType.JSON, ContentType = ContentType.JSON, Headers = new Dictionary <string, string>() { { HDR_AUTHORIZATION, getAuthHeader(session.User.Credentials) }, { HDR_X_API_VERSION, API_VERSION } }, Body = body != null?body.ToJSON(JSONWritingOptions.Compact) : null }; return(WebClient.GetJsonAsDynamic(prms)); }
public static XDocument GetXML(string uri, IWebClientCaller caller, HTTPRequestMethod method = HTTPRequestMethod.GET, IDictionary<string, string> queryParameters = null, IDictionary<string, string> bodyParameters = null, IDictionary<string, string> headers = null) { return GetXML(new Uri(uri), caller, method, queryParameters, bodyParameters, headers); }
public static XDocument GetXML(Uri uri, IWebClientCaller caller, HTTPRequestMethod method = HTTPRequestMethod.GET, IDictionary<string, string> queryParameters = null, IDictionary<string, string> bodyParameters = null, IDictionary<string, string> headers = null) { string responseStr = GetString(uri, caller, method, queryParameters: queryParameters, bodyParameters: bodyParameters, headers: headers); return string.IsNullOrWhiteSpace(responseStr) ? null : XDocument.Parse(responseStr); }
public static JSONDataMap GetValueMap(string uri, IWebClientCaller caller, HTTPRequestMethod method = HTTPRequestMethod.GET, IDictionary<string, string> queryParameters = null, IDictionary<string, string> bodyParameters = null, IDictionary<string, string> headers = null) { return GetValueMap(new Uri(uri), caller, method, queryParameters, bodyParameters, headers); }
public static JSONDataMap GetValueMap(Uri uri, IWebClientCaller caller, HTTPRequestMethod method = HTTPRequestMethod.GET, IDictionary<string, string> queryParameters = null, IDictionary<string, string> bodyParameters = null, IDictionary<string, string> headers = null) { string responseStr = GetString(uri, caller, method, queryParameters: queryParameters, bodyParameters: bodyParameters, headers: headers); var dict = Utils.ParseQueryString(responseStr); return dict; }
public static JSONDataMap GetJson(Uri uri, IWebClientCaller caller, HTTPRequestMethod method = HTTPRequestMethod.GET, IDictionary<string, string> queryParameters = null, IDictionary<string, string> bodyParameters = null, IDictionary<string, string> headers = null) { string responseStr = GetString(uri, caller, method, queryParameters: queryParameters, bodyParameters: bodyParameters, headers: headers); return string.IsNullOrWhiteSpace(responseStr) ? null : responseStr.JSONToDataObject() as JSONDataMap; }
private dynamic Send(HTTPRequestMethod method, string contentType, Uri uri, Stream body = null) { if (m_AccessToken.IsNullOrEmpty()) RefreshAccessToken(); var res = TrySend(method, contentType, uri, body); return res.GetJSON(); }
/// <summary> /// Tries to send a request m_NumberOfAttempts of times /// </summary> private HttpWebResponse TrySend(HTTPRequestMethod method, string contentType, Uri uri, Stream body = null) { for (var n = 0; n < m_Attempts; ++n) { try { var req = CreateRequest(method, contentType, uri, body); return SendRequest(req); } catch (System.Net.WebException ex) { var retry = CanRetryRequest(ex); if (!retry) { throw new FileSystemException(ex.Message, ex); } var rnd = new Random(); Thread.Sleep((1 << n) * 1000 + rnd.Next(1001)); } } return null; }
private XDocument getResponse(BraintreeSession session, Uri uri, XDocument body = null, HTTPRequestMethod method = HTTPRequestMethod.POST) { if (!session.IsValid) throw new PaymentException("Braintree: " + StringConsts.PAYMENT_BRAINTREE_SESSION_INVALID.Args(this.GetType().Name + ".getResponse")); var prms = new WebClient.RequestParams() { Caller = this, Uri = uri, Method = method, AcceptType = ContentType.XML_APP, ContentType = ContentType.XML_APP, Headers = new Dictionary<string, string>() { { HDR_AUTHORIZATION, getAuthHeader(session.User.Credentials) }, { HDR_X_API_VERSION, API_VERSION } }, Body = body != null ? new XDeclaration("1.0", "UTF-8", null).ToString() + body.ToString(SaveOptions.DisableFormatting) : null }; try { return WebClient.GetXML(prms); } catch (System.Net.WebException ex) { StatChargeError(); var resp = (System.Net.HttpWebResponse)ex.Response; if (resp != null && resp.StatusCode == (System.Net.HttpStatusCode)422) { using (var sr = new StreamReader(resp.GetResponseStream())) { var respStr = sr.ReadToEnd(); var response = respStr.IsNotNullOrWhiteSpace() ? XDocument.Parse(respStr) : null; if (response != null) { var apiErrorResponse = response.Element("api-error-response"); throw new PaymentException(apiErrorResponse.Element("message").Value, ex); } } } throw; } catch { throw; } }
private XDocument getResponse(BraintreeSession session, Uri uri, XDocument body = null, HTTPRequestMethod method = HTTPRequestMethod.POST) { var prms = new WebClient.RequestParams(this) { Method = method, AcceptType = ContentType.XML_APP, ContentType = ContentType.XML_APP, Headers = new Dictionary <string, string>() { { HDR_AUTHORIZATION, ((BraintreeCredentials)session.User.Credentials).AuthorizationHeader }, { HDR_X_API_VERSION, API_VERSION } }, Body = body != null ? new XDeclaration("1.0", "UTF-8", null).ToString() + body.ToString(SaveOptions.DisableFormatting) : null }; try { return(WebClient.GetXML(uri, prms)); } catch (System.Net.WebException ex) { StatChargeError(); var resp = (System.Net.HttpWebResponse)ex.Response; if (resp != null && resp.StatusCode == (System.Net.HttpStatusCode) 422) { using (var sr = new StreamReader(resp.GetResponseStream())) { var respStr = sr.ReadToEnd(); var response = respStr.IsNotNullOrWhiteSpace() ? XDocument.Parse(respStr) : null; if (response != null) { var apiErrorResponse = response.Element("api-error-response"); throw new PaymentException(apiErrorResponse.Element("message").Value, ex); } } } throw; } }
public static void SendData(HTTPRequestMethod method, string url, UnityAction <UnityWebRequest> callback = null, KeyValuePair <string, string>[] headers = default, string body = "") => Instance.StartCoroutine(SendDataCoroutine(method, url, callback, headers, body));
public static string GetString(Uri uri, IWebClientCaller caller, HTTPRequestMethod method = HTTPRequestMethod.GET, IDictionary<string, string> queryParameters = null, IDictionary<string, string> bodyParameters = null, string body = null, IDictionary<string, string> headers = null) { RequestParams request = new RequestParams() { Uri = uri, Caller = caller, Method = method, QueryParameters = queryParameters, BodyParameters = bodyParameters, Body = body, Headers = headers }; return GetString(request); }
private HttpWebRequest CreateRequest(HTTPRequestMethod method, string contentType, Uri uri, Stream body = null) { var fullUri = new Uri(ApiUrls.GoogleApi(), uri); var req = WebRequest.CreateHttp(fullUri); req.Method = method.ToString(); if (m_Timeout > 0) { req.Timeout = m_Timeout; } req.Headers.Add(HEADER_AUTHORIZATION, "Bearer " + m_AccessToken); req.UserAgent = USER_AGENT; var canHaveBody = method == HTTPRequestMethod.PUT || method == HTTPRequestMethod.POST || method == HTTPRequestMethod.PATCH; if (canHaveBody && body != null) { req.ContentType = contentType; req.ContentLength = body.Length; using (var stream = req.GetRequestStream()) { body.Position = 0; body.CopyTo(stream); stream.Flush(); stream.Close(); } } return req; }
public static JSONDynamicObject GetJsonAsDynamic(string uri, IWebClientCaller caller, HTTPRequestMethod method = HTTPRequestMethod.GET, IDictionary<string, string> queryParameters = null, IDictionary<string, string> bodyParameters = null, IDictionary<string, string> headers = null) { return GetJsonAsDynamic(new Uri(uri), caller, method, queryParameters, bodyParameters, headers); }