/// <summary> /// Sends the game data to the API. /// </summary> /// <param name="gameData">Game data to be sent.</param> private void SendGameData(GameData gameData) { gameData.TimeLimit = _config.TimePerGame == 0 ? _config.TimePerTask * _config.TasksPerGame : _config.TimePerGame; gameData.TimeAdded = DateTime.Now; var headers = new string[] { "Content-Type: application/json" }; var serializedData = JsonConvert.SerializeObject(gameData); using (var client = new HTTPClient()) { client.ConnectToHost(Constants.ApiHost); while (client.GetStatus() == HTTPClient.Status.Resolving || client.GetStatus() == HTTPClient.Status.Connecting) { client.Poll(); } client.Request(HTTPClient.Method.Post, Constants.ApiDataCollectorUrl, headers, serializedData); while (client.GetStatus() == HTTPClient.Status.Requesting) { client.Poll(); } } }
protected override void UpdateContentData(HTTPClient client, HTTPResponse response) { uint connectionID = client.ConnectionID; ulong length = Bindings._URLClientGetPendingResponseContentLength(connectionID); // no data pending? if (length <= 0) { return; } ulong copied; // buffer read pending data do { if (_contentDataBuffer == null) { _contentDataBuffer = new byte[RESPONSE_BUFFER_SIZE]; } copied = Bindings.URLClientMovePendingResponseContent(connectionID, _contentDataBuffer, RESPONSE_BUFFER_SIZE); if (copied <= (ulong)0) { break; } OnDidReceiveData(response, _contentDataBuffer, copied); response.receivedContentLength += copied; } while (copied == RESPONSE_BUFFER_SIZE); }
public async void Download(int provider, string response, Dictionary <string, string> parameters, HttpListenerContext context) { if (string.IsNullOrEmpty(parameters["epglist"])) { return; } lock (parameters) { var epg_url = GetEPGProviderURL(int.Parse(parameters["epglist"])).Result; if (!string.IsNullOrEmpty(epg_url)) { var prov = ChannelProvider.GetProviderNameByID(db, provider); var wc = new HTTPClient(epg_url); wc.GetResponse(prov.Result); wc.HTTPClientResponse += (sender, e) => { var res = e.Data; if (!string.IsNullOrEmpty(res)) { EPGData = ImportFormJson(res, int.Parse(parameters["epglist"])).Result; } }; } } Task.Run(() => MakeResponse(provider, response, BackendAction.Download, parameters, context)); }
public string IVSTest(string isn, string responseContentText) { ReplayDevice device = new ReplayDevice(); char[] separator = new char[] { ' ' }; string[] textArray = responseContentText.Split(separator); char[] trimChars = new char[] { '"' }; device.isn = textArray[1].Substring(4).Trim(trimChars); char[] chArray3 = new char[] { '"' }; device.ip = textArray[2].Substring(3).Trim(chArray3); char[] chArray4 = new char[] { '"' }; device.port = textArray[3].Substring(5).Trim(chArray4); try { string xml = HTTPClient.GetAsString("http://" + device.ip + ":" + device.port + "/ivs-IVSGetUnitInfo", 0x3a98); XmlDocument document = new XmlDocument(); document.LoadXml(xml); foreach (XmlNode node in document.SelectNodes("/UnitInfo")) { XmlElement element = node as XmlElement; if (element != null) { return(element.GetAttribute("nickname")); } } } catch { } return(null); }
private void AuthCallback(ILoginResult result) { if (FB.IsLoggedIn) { // AccessToken class will have session details var aToken = AccessToken.CurrentAccessToken; FBAccessToken fbAccessToken = new FBAccessToken(); fbAccessToken.TokenString = aToken.TokenString; fbAccessToken.UserType = "Instructor"; StartCoroutine( HTTPClient.Post("/updateUser", JsonUtility.ToJson(fbAccessToken), statusCode => { if (statusCode == "200") { SceneManager.LoadScene("SetupMeditationRoom"); } else { HFTDialog.MessageBox("Authentication error", "Facebook authentication failed.", () => { Debug.Log("statusCode"); Debug.Log(statusCode); }); } }) ); } else { Debug.Log("Error"); Debug.Log(result); Debug.Log(result.Error); Debug.Log("User cancelled login"); } }
IEnumerator DemoFilePost() { _test = "DemoFilePost"; string srcPath = Application.temporaryCachePath; srcPath = System.IO.Path.Combine(srcPath, "data"); byte[] data = Encoding.UTF8.GetBytes("hello\nworld\n!!!"); using (FileStream stream = new FileStream(srcPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) { stream.Write(data, 0, data.Length); } HTTPRequest request = new HTTPRequest(); request.SetURL("http://www.hashemian.com/tools/form-post-tester.php/test123"). SetContentFromPath(srcPath, "application/octet-stream"). Post(); using (_client = new HTTPClient(request)) { yield return(StartCoroutine(_client.WaitUntilDone())); DebugAll(_client); } }
internal static List <Trade> GetTrades(int userId) { List <Trade> TradesList = new List <Trade>(); Dictionary <string, object> userIdDict = new Dictionary <string, object>() { { "user_id", userId } }; var JsonResult = HTTPClient.SendRequest(HTTPClient.Address + "/get_trades", userIdDict); var Trades = JsonConvert.DeserializeObject <List <Dictionary <string, object> > >(JsonResult["results"].ToString()); if (Convert.ToInt32(JsonResult["success"]) == 1) { foreach (Dictionary <string, object> Dictionary in Trades) { Trade trade = Trade.FromJson(Dictionary); TradesList.Add(trade); } return(TradesList); } else { PrintError(JsonResult["success"].ToString()); return(null); } }
internal static List <Wallet> GetWallets(int userId) { List <Wallet> UserWallets = new List <Wallet>(); Dictionary <string, object> userIdData = new Dictionary <string, object> { { "user_id", userId } }; var JsonResult = HTTPClient.SendRequest(HTTPClient.Address + "/get_wallets", userIdData); var WalletsList = JsonConvert.DeserializeObject <List <Dictionary <string, object> > >(JsonResult["results"].ToString()); if (Convert.ToInt32(JsonResult["success"]) == 1) { foreach (Dictionary <string, object> Dictionary in WalletsList) { Wallet wallet = Wallet.FromJson(Dictionary); UserWallets.Add(wallet); } return(UserWallets); } else { PrintError(JsonResult["message"].ToString()); return(null); } }
/// <summary> /// Get a flight plan from the database and return it. /// </summary> /// <param name="id"> The id of the flight plan. </param> /// <returns> The flight plan. </returns> public async Task <FlightPlan> GetFlightPlan(string id) { // Try get the flight plan from the local data base. FlightPlan local = await flightsDB.GetFlightPlan(id); if (local != null) { return(local); } /* If flight plan not in local data base, try to retrieve it from an * external server. * Get the server in which the flight plan is located. */ FlightServer relevantServer = await flightsServersDB.GetFlightServer(id); if (relevantServer != null) { // Ask the external server for the flight plan. Server server = await serversDB.GetServer(relevantServer.ServerId); IHTTPClient client = new HTTPClient(server); return(await client.GetFlightPlan(id)); } return(null); }
internal static List <Coin> GetCoinPrices(List <string> SymbolList) { List <Coin> ResultCoins = new List <Coin>(); Dictionary <string, object> symbolData = new Dictionary <string, object>() { { "symbols", SymbolList } }; var JsonResult = HTTPClient.SendRequest(HTTPClient.Address + "/get_coins", symbolData); var CoinLists = JsonConvert.DeserializeObject <List <Dictionary <string, object> > >(JsonResult["results"].ToString()); if (Convert.ToInt32(JsonResult["success"]) == 1) { foreach (Dictionary <string, object> Dictionary in CoinLists) { Coin coin = Coin.FromJson(Dictionary); ResultCoins.Add(coin); } return(ResultCoins); } else { PrintError(JsonResult["message"].ToString()); return(null); } }
private void Start() { HTTPClient.Create(); UserSingleton.Create(); LoginInit(); }
protected override void UpdateContentData(HTTPClient client, HTTPResponse response) { uint connectionID = client.ConnectionID; ulong length = Bindings._URLClientGetPendingResponseContentLength(connectionID); // no data pending? if (length <= 0) { return; } ulong copied; // buffer read pending data do { if (_contentDataBuffer == null) { _contentDataBuffer = new byte[RESPONSE_BUFFER_SIZE]; } copied = Bindings.URLClientMovePendingResponseContent(connectionID, _contentDataBuffer, RESPONSE_BUFFER_SIZE); if (copied <= (ulong)0) { break; } OnDidReceiveData(response, _contentDataBuffer, copied); response.receivedContentLength += copied; } while (copied == RESPONSE_BUFFER_SIZE); }
public RealtimeOrderBookHandler(HTTPClient httpClient, WebsocketClient websocketClient) { _httpClient = httpClient; _websocketClient = websocketClient; BooksForSymbols = new Dictionary <string, RealTimeOrderbook>(); _websocketClient.DiffDepth.OnDiffDepthReceived += DiffDepth_OnDiffDepthReceived; }
async Task <bool> TestChannelUrl(string name, string url, string ua) { if (string.IsNullOrEmpty(url)) { return(false); } if (url.StartsWith("rtmp")) { return(true); } var result = false; var hc = new HTTPClient(url, "HEAD"); Task.Run(() => hc.GetResponse(name)); hc.HTTPClientResponse += (sender, e) => { switch (hc.StatusCode) { case HttpStatusCode.OK: case HttpStatusCode.Moved: result = true; break; default: result = false; break; } }; return(result); }
public T GetItemByID <T>(string id) { T output; string data = HTTPClient.GetAsync(GetEndPoint <T>(id)).Result.Content.ReadAsStringAsync().Result; output = JsonConvert.DeserializeObject <T>(data); return(output); }
public Element GetElement(string tableID, string elementId) { Element output; string data = HTTPClient.GetAsync(GetEndPoint <Table>(tableID) + "/" + elementId).Result.Content.ReadAsStringAsync().Result; output = JsonConvert.DeserializeObject <Element>(data); return(output); }
public Proxy(Uri uri) { ApiMessageHandler apiMessageHandler = new ApiMessageHandler(new WebRequestHandler { UseCookies = false }); this._httpClient = new HTTPClient(uri, apiMessageHandler); }
void Start () { input_username = input_username.GetComponent<InputField> (); input_password = input_password.GetComponent<InputField> (); login_client = GetComponent<HTTPClient> (); attempt_result = 0; }
public ServerFileInfoResponse GetServerResponse(IPEndPoint ipEndPoint, string hash) { ServerFileInfoResponse response = new ServerFileInfoResponse(); List<IPEndPoint> ipList = new List<IPEndPoint>(); Uri requestUri = new Uri(string.Format("http://{0}:{1}/filename|{2}", ipEndPoint.Address, ipEndPoint.Port, hash)); HTTPClient client = new HTTPClient(); string xml = client.DownloadString(requestUri); XDocument doc = XDocument.Parse(xml); var userlist = from user in doc.Descendants("User") select user; foreach (XElement element in userlist) { if(element.Attribute("IP") != null && element.Attribute("Port") != null) { string ipStr = element.Attribute("IP").Value; string portStr = element.Attribute("Port").Value; int port; IPAddress ip; if(int.TryParse(portStr, out port) && IPAddress.TryParse(ipStr, out ip)) { IPEndPoint endPoint = new IPEndPoint(ip, port); ipList.Add(endPoint); } } } response.IpList = ipList; var fileSize = doc.Descendants("FileSize"); if(fileSize.Count() != 0 && fileSize.First().Attribute("Size") != null) { long size; string sizeStr = fileSize.First().Attribute("Size").Value; if (long.TryParse(sizeStr, out size)) { response.FileSize = size; } } var blocks = doc.Descendants("Blocks"); if(blocks.Count() != 0 && blocks.First().Attribute("Number") != null) { int blockNum; string blockNumStr = blocks.First().Attribute("Number").Value; if(int.TryParse(blockNumStr, out blockNum)) { response.BlockNum = blockNum; } } return response; }
public void switchOff() { if (httpClient == null) { httpClient = new HTTPClient(this); } httpClient.callAPIAsync(getUrlString(1, false)); }
public void Init(Wallet w, SequenceEnsureMode seqEnsureMode) { _wallet = w; _httpClient = new HTTPClient(w.Env.Network); this.sequenceEnsureMode = seqEnsureMode; BroadcastLockObject = new object(); _ws = new Websockets.WebsocketClient(w.Env.Network); _rtBooks = new RealtimeOrderBookHandler(_httpClient, _ws); }
/// <summary> /// Get all the flights from this server and other servers. /// </summary> /// <param name="relativeTo"> Time at the student's. </param> /// <returns> All the flights. </returns> public async Task <IList <Flight.Flight> > GetAllFlightsSync(DateTime relativeTo) { // Get first all local flights. Task <IList <Flight.Flight> > localFlights = GetAllFlights(relativeTo); /* Create a list contains lists of external flights. * Each inner list represents flights from a specifiec server. */ IList <Task <IList <Flight.Flight> > > externalFlights = new List <Task <IList <Flight.Flight> > >(); IList <KeyValuePair <string, string> > serversUpdates = new List <KeyValuePair <string, string> >(); await foreach (Server server in serversDB.GetAllServers()) { // For each server, ask it for all its flights. HTTPClient client = new HTTPClient(server); Task <IList <Flight.Flight> > externals = client.GetFlights( relativeTo.ToString("yyyy-MM-ddTHH:mm:ssZ")); IList <Flight.Flight> res = await externals; if (res == null) { continue; } foreach (Flight.Flight flight in res) { /* Change isExternal property of the flight to true, * as it was retrieved from an external server. */ flight.IsExternal = true; serversUpdates.Add(new KeyValuePair <string, string>( flight.FlightID, server.Id)); } externalFlights.Add(externals); } IList <Flight.Flight> temp = await localFlights; /* Join all the lists from the servers and the list of the local flight to * one list of flights. */ foreach (Task <IList <Flight.Flight> > flightsList in externalFlights) { temp = temp.Concat(await flightsList).ToList(); } foreach (KeyValuePair <string, string> pair in serversUpdates) { /* Add the id of the flight to the data base. Connect it to its server. * Next time we want the flight plan we can * simply ask it from the relevant server. */ await flightsServersDB.AddFlightServer( new Servers.FlightServer(pair.Key, pair.Value)); } return(temp); }
public List <Release> GetReleasesForTable(string tableID, bool listOnly = false) { List <Release> output; string attr = listOnly ? "?tableID=" + tableID + "&list=true" : "?tableID=" + tableID; string data = HTTPClient.GetAsync(GetEndPoint <Release>() + attr).Result.Content.ReadAsStringAsync().Result; output = JsonConvert.DeserializeObject <List <Release> >(data); return(output); }
IEnumerator DemoSimple() { _test = "DemoSimple"; using (_client = new HTTPClient("unity3d.com")) { yield return StartCoroutine(_client.WaitUntilDone()); DebugAll(_client); } }
void DebugClient(HTTPClient _client) { IHTTPResponse response = _client.Response; _log = _client.ToString(); if (response == null) { _log += "\nAwaiting response..."; } }
IEnumerator DemoSimple() { _test = "DemoSimple"; using (_client = new HTTPClient("unity3d.com")) { yield return(StartCoroutine(_client.WaitUntilDone())); DebugAll(_client); } }
private async Task <PaymentResult> Validate3D(VerifyPaymentModel paymentModel, IFormCollection collection) { var config = (YKBConfiguration)ProviderConfiguration; string encKey = config.HashKey; if (paymentModel.Order.CurrencyCode.IsEmpty()) { paymentModel.Order.CurrencyCode = "TL"; } Log.Information($"YKBProvider:ENC:{encKey}"); string xid = collection["Xid"]; var amount = (decimal.Parse(collection["Amount"], new CultureInfo("tr-TR"))).ToString("0", new CultureInfo("en-US")); string firstShaString = encKey + ';' + config.TerminalId; string firstHash = HashHelper.GetSHA256(firstShaString); string macShaString = xid + ';' + amount + ';' + paymentModel.Order.CurrencyCode + ';' + config.MerchantId + ';' + firstHash; string mac = HashHelper.GetSHA256(macShaString); Log.Information($"YKBProvider:firstShaString:{firstShaString}"); Log.Information($"YKBProvider:firstHash:{firstHash}"); Log.Information($"YKBProvider:sha256String:{macShaString}"); Log.Information($"YKBProvider:mac:{mac}"); paymentModel.Attributes.Add(new SanalPosTRAttribute { Key = "mac", Value = mac }); string template = TemplateHelper.ReadEmbedResource($"{EmbededDirectory}.3D_Resolve.xml"); string postData = TemplateHelper.PrepaireXML(new ViewModel { Use3DSecure = true, Configuration = ProviderConfiguration, Attributes = paymentModel.Attributes }, template); var post = GetPostForm(); post.Content = System.Net.WebUtility.UrlEncode(postData); HTTPClient client = new HTTPClient(EndPointConfiguration.BaseUrl); var result = await client.Post(EndPointConfiguration.ApiEndPoint, post, Handler); if (TemplateHelper.GetInlineContent(result.ServerResponseRaw, "mdStatus") != "1") { result.Status = false; result.ErrorCode = TemplateHelper.GetInlineContent("mdErrorMessage", result.ServerResponseRaw); } return(result); }
public List <ChangeSet> GetChangeSetsForTable(string tableID, bool ignoreChanges = false, bool listOnly = false) { List <ChangeSet> output; string attr = ignoreChanges ? "?tableID=" + tableID + "&ignoreChanges=true" : "?tableID=" + tableID; attr = listOnly ? attr + "&list=true" : attr; string data = HTTPClient.GetAsync(GetEndPoint <ChangeSet>() + attr).Result.Content.ReadAsStringAsync().Result; output = JsonConvert.DeserializeObject <List <ChangeSet> >(data); return(output); }
public async void Update(int provider, string response, Dictionary <string, string> parameters, HttpListenerContext context) { var channels = GetChannels(); foreach (var channel in channels) { foreach (var server in channel.Servers) { if (server.URL.StartsWith("rtmp")) { continue; } var hc = new HTTPClient(server.URL); hc.UserAgent = Functions.GetUseragentByID(db, server.UserAgent).Result; await Task.Run(() => hc.GetResponse(channel.Name)).ContinueWith(c => { if (hc.StatusCode != HttpStatusCode.OK && hc.StatusCode != HttpStatusCode.Moved) { lock (Channels.Members) Channels.Members[channel.Name].Servers.Remove(server); Task.Run(() => Console.WriteLine("Removing URL: {0} (Status Code: {1})...", server.URL, hc.StatusCode)); } }); } } foreach (var item in channels) { var n = item.Name.FirstCharUpper(db).Result; var ch_nameid = AddChannelName(db, n.Trim()).Result; var ch_logoid = AddChannelLogo(item.Logo, item.Provider).Result; var ch_epgid = AddChannelEPGID(item.ID, item.Provider).Result; if (db.Count("channels", "name", ch_nameid).Result == 0 && db.Count("channels", "logo", ch_logoid).Result == 0 && db.Count("channels", "epgid", ch_epgid).Result == 0) { var chan_id = InsertChannel(ch_nameid, ch_logoid, ch_epgid, item.Provider, item.Type, item.ChanNo); for (var i = 0; i < item.Servers.Count; i++) { if (db.Count("servers", "url", item.Servers[i].URL).Result == 0) { await Task.Run(() => db.SQLInsert(string.Format("INSERT INTO servers (url, channel, type) VALUES ('{0}','{1}','{2}')", item.Servers[i].URL, chan_id.Result, item.Servers[i].Type))); } } } } }
public async virtual Task <PaymentResult> ProcessPayment(PaymentModel paymentModel) { Log.Information($"ProcessPayment-Start"); //after may be fluent validation here string resource = string.Empty; if (paymentModel.Use3DSecure) { resource = $"{EmbededDirectory}.3D.xml"; } else { resource = $"{EmbededDirectory}.Pay.xml"; } string embededResource = TemplateHelper.ReadEmbedResource(resource); Log.Information($"ProcessPayment-ReadEmbedResource"); string viewModel = OnCompilingTemplate(paymentModel, embededResource); Log.Information($"ProcessPayment-CompiledTemplate"); if (viewModel.IsEmpty() == false) { var form = GetPostForm(); form.Content = viewModel; if (paymentModel.Use3DSecure == false) { Log.Information($"ProcessPayment-HttpPost - NonUse3DSecure"); HTTPClient httpClient = new HTTPClient(EndPointConfiguration.BaseUrl); return(await httpClient.Post(EndPointConfiguration.ApiEndPoint, form, Handler)); } else { Log.Information($"ProcessPayment-HttpPost - Use3DSecure"); PaymentResult paymentResult = new PaymentResult(); paymentResult.IsRedirectContent = true; paymentResult.ServerResponseRaw = viewModel; paymentResult.Status = true; return(paymentResult); } } else { throw new ApplicationException($"{this.GetType().Name} template is empty"); } }
void Awake() { DontDestroyOnLoad(this); if (instance == null) { instance = this; } else { Destroy(this); } }
private static byte[] getRatePage() { HTTPClient hc = new HTTPClient( ///////////////////////////////////////////////// $_git:secret ); hc.connectionTimeoutMillis = 10000; hc.timeoutMillis = 15000; hc.noTrafficTimeoutMillis = 5000; hc.get(); return(hc.resBody); }
void DebugTimeAndSpeed(HTTPClient _client) { float duration = (Time.realtimeSinceStartup - _initialTime); _log += "\nElapsed (secs): " + duration; if ((duration > 0f) && (_client.Response != null)) { float speed = (_client.Response.ReceivedContentLength / 1024f) / duration; _log += "\nAvg Speed (KBytes/sec): " + speed; } }
public void UseInterfaces(HTTPClient httpSession, string[] arguments) { foreach (KeyValuePair <string, WebInterface> webInt in interfaces) { if (webInt.Key != arguments[0]) { continue; } webInt.Value.Use(httpSession, arguments); break; } }
IEnumerator DemoFormPost() { _test = "DemoFormPost"; HTTPRequest request = new HTTPRequest(); request.SetURL("http://www.hashemian.com/tools/form-post-tester.php/test123"). SetContentString("foo=bar&cafe=babe", "application/octet-stream"). Post(); using (_client = new HTTPClient(request)) { yield return StartCoroutine(_client.WaitUntilDone()); DebugAll(_client); } }
IEnumerator DemoBasicAuthClient() { _test = "DemoBasicAuthClient"; HTTPRequest request = new HTTPRequest(); request.SetURL("http://browserspy.dk/password-ok.php"). SetAuthCredential("test", "test"); using (_client = new HTTPClient(request)) { yield return StartCoroutine(_client.WaitUntilDone()); DebugAll(_client); } }
IEnumerator DemoRedirectControl() { _test = "DemoRedirectControl"; HTTPRequest request = new HTTPRequest(); request.SetURL("https://google.com"). AppendQueryParameter("q", "unity"); HTTPResponseMemoryStreamHandler responseHandler = new HTTPResponseMemoryStreamHandler(); responseHandler.SetAllowFollowRedirects(true); responseHandler.SetMaxRedirectCount(10); using (_client = new HTTPClient(request, responseHandler)) { yield return StartCoroutine(_client.WaitUntilDone()); DebugAll(_client); } }
IEnumerator DemoTimeoutControl() { _test = "DemoTimeoutControl"; HTTPRequest request = new HTTPRequest(); request.SetURL("http://www.wikipedia.com"); using (_client = new HTTPClient(request)) { _client.ConnectionTimeout = 0.01f; yield return StartCoroutine(_client.WaitUntilDone()); DebugAll(_client); Error err = _client.Error; if (err != null) { _log += "\n\nIs Timeout Error? " + (err.IsKnownCode(Error.KnownCode.ConnectionTimeoutError) ? "YES" : "NO"); } } }
void DebugTimeAndSpeed(HTTPClient _client) { float duration = (Time.realtimeSinceStartup - _initialTime); _log += "\nElapsed (secs): " + duration; if ((duration > 0f) && (_client.Response != null)) { float speed = (_client.Response.ReceivedContentLength / 1024f) / duration; _log += "\nAvg Speed (KBytes/sec): " + speed; } }
IEnumerator DemoQueryHeaderAndCookies() { _test = "DemoQueryHeaderAndCookies"; HTTPRequest request = new HTTPRequest(); request.SetURL("http://www.google.com"). AppendQueryParameter("q", "unity"). SetHeader("User-Agent", "dummy user agent"). AppendCookie("name", "value"). Get(); using (_client = new HTTPClient(request)) { yield return StartCoroutine(_client.WaitUntilDone()); DebugAll(_client); } }
/// <summary> /// Main. /// </summary> /// <param name="myArgs">The arguments.</param> public static void Main(String[] myArgs) { #region Start TCPServers //var _TCPServer1 = new TCPServer(new IPv4Address(new Byte[] { 192, 168, 178, 31 }), new IPPort(2001), NewConnection => // { // NewConnection.WriteToResponseStream("Hello world!" + Environment.NewLine + Environment.NewLine); // NewConnection.Close(); // }, true); //Console.WriteLine(_TCPServer1); // The first line of the repose will be served from the CustomTCPConnection handler. var _TCPServer2 = new TCPServer<CustomTCPConnection>(IPv4Address.Any, new IPPort(2002), NewConnection => { NewConnection.WriteToResponseStream("...world!" + Environment.NewLine + Environment.NewLine); NewConnection.Close(); }, true); Console.WriteLine(_TCPServer2); #endregion #region Start HTTPServers // Although the socket listens on IPv4Address.Any the service is // configured to serve clients only on http://localhost:8181 // More details within DefaultHTTPService.cs var _HTTPServer1 = new HTTPServer(IPv4Address.Any, new IPPort(8181), Autostart: true) { ServerName = "Default Hermod Demo" }; Console.WriteLine(_HTTPServer1); // This service uses a custom HTTPService defined within IRESTService.cs var _HTTPServer2 = new HTTPServer<IRESTService>(IPv4Address.Any, IPPort.HTTP, Autostart: true) { ServerName = "Customized Hermod Demo" }; Console.WriteLine(_HTTPServer2); #endregion #region UDP Servers var _UDPServer1 = new UDPServer(new IPPort(5555), NewPacket => { //NewPacket.Data = new Byte[10]; // NewPacket.Close(); }, true); #endregion var _client1 = new HTTPClient(IPv4Address.Localhost, IPPort.HTTP); var _request0 = _client1.GET("/HelloWorld"). SetHost("localhorst"). AddAccept(HTTPContentType.TEXT_UTF8, 1); var _request1 = _client1.GET("/HelloWorld"). SetHost("localhorst"). AddAccept(HTTPContentType.HTML_UTF8, 1); //WriteRequest(_request0.EntireRequestHeader); //_client1.Execute(_request0, response => WriteResponse(response.Content.ToUTF8String())). // ContinueWith(HTTPClient => { WriteRequest(_request1.EntireRequestHeader); return HTTPClient.Result; }). // ContinueWith(HTTPClient => HTTPClient.Result.Execute(_request1, response => WriteResponse(response.Content.ToUTF8String()))). // Wait(); var _client2 = new HTTPClient(IPv4Address.Parse("188.40.47.229"), IPPort.HTTP); var _requestA = _client2.GET("/"). SetProtocolVersion(HTTPVersion.HTTP_1_1). SetHost("www.ahzf.de"). SetUserAgent("Hermod HTTP Client v0.1"). SetConnection("keep-alive"). AddAccept(HTTPContentType.HTML_UTF8, 1); var _requestB = _client2.GET("/nfgj"). SetProtocolVersion(HTTPVersion.HTTP_1_1). SetHost("www.ahzf.de"). SetUserAgent("Hermod HTTP Client v0.1"). SetConnection("keep-alive"). AddAccept(HTTPContentType.HTML_UTF8, 1); WriteRequest(_requestA); _client2.Execute(_requestA, response => WriteResponse(response)). ContinueWith(Client => Client.Result.Execute(_requestB, response => WriteResponse(response))); var _req23a = new HTTPRequestBuilder(). SetHTTPMethod (HTTPMethod.GET). SetProtocolName ("µHTTP"). SetProtocolVersion (new HTTPVersion(2, 0)). SetHost ("localhorst"). SetUserAgent ("Hermod µHTTP Client"). SetContent ("This the HTTP content..."); _req23a.QueryString.Add("name", "alice"). Add("friend", "bob"). Add("friend", "carol"); var _req23b = new HTTPRequestBuilder() { HTTPMethod = HTTPMethod.GET, ProtocolName = "µHTTP", ProtocolVersion = new HTTPVersion(2, 0), Host = "localhorst", UserAgent = "Hermod µHTTP Client", Content = "This the HTTP content...".ToUTF8Bytes() }; // var Response = new TCPClientRequest("localhost", 80).Send("GETTT / HTTP/1.1").FinishCurrentRequest().Response; Console.ReadLine(); Console.WriteLine("done!"); }
IEnumerator DemoBigFileDownload() { _test = "DemoBigFileDownload"; string url = "http://netstorage.unity3d.com/unity/unity-4.1.5.dmg"; string destinationPath = Application.temporaryCachePath; destinationPath = System.IO.Path.Combine(destinationPath, "unity-4.1.5.dmg"); using (_client = new HTTPClient(url, destinationPath)) { DebugClient(_client); while (!_client.IsDone) { DebugClient(_client); DebugTimeAndSpeed(_client); yield return null; } DebugAll(_client); } }
void DebugAll(HTTPClient _client) { DebugClient(_client); DebugResponseString(_client); DebugTimeAndSpeed(_client); }
void DebugClient(HTTPClient _client) { IHTTPResponse response = _client.Response; _log = _client.ToString(); if (response == null) { _log += "\nAwaiting response..."; } }
void DebugResponseString(HTTPClient _client) { if (_client.Response != null) { _log += "\n\nResponse Content\n"; string str = _client.Response.ContentToString(); if ((str != null) && (str.Length > 1024)) { str = str.Substring(0, 1024) + "... (shortened)"; } _log += str; } }
IEnumerator DemoAcceptInvalidHTTPSCertificates() { _test = "DemoAcceptInvalidHTTPSCertificates"; HTTPRequest request = new HTTPRequest(); request.SetURL("https://google.com"). AppendQueryParameter("q", "unity"); HTTPResponseMemoryStreamHandler responseHandler = new HTTPResponseMemoryStreamHandler(); responseHandler.SetAllowInvalidSSLCertificates(true); using (_client = new HTTPClient(request, responseHandler)) { yield return StartCoroutine(_client.WaitUntilDone()); DebugAll(_client); } }
IEnumerator DemoBigFileIntegrityTest() { _test = "DemoBigFileIntegrityTest"; // By default, Unity-URLClient loads data into memory, and therefore // loading a big file into memory like this, is NOT recommended! // In order to reduce big data buffer exchange between native and unity side, // and in order to have a constantly updated buffer in unity side, Unity-URLClient // periodically buffers data from native into unity side. For that reason, // we're testing here if the data is correctly assembled back into one // piece by checking the MD5 of the downloaded data with the expected MD5. // // See DemoBigFileDownload() below for how to download directly into a file. string url = "http://imgsrc.hubblesite.org/hu/db/images/hs-2012-01-a-print.jpg"; using (_client = new HTTPClient(url)) { DebugClient(_client); while (!_client.IsDone) { DebugClient(_client); DebugTimeAndSpeed(_client); yield return null; } DebugAll(_client); string result; Error err = _client.Error; if ((err != null) || (_client.Response == null)) { result = "ERROR: Integrity check aborted"; } else { byte[] bytes = _client.Response.ContentToBytes(); if (bytes == null) { result = "ERROR: Integrity check aborted (NO DATA RECEIVED)"; } else if (bytes.Length != 3107578) { result = "ERROR: Integrity check aborted (LENGTH MISMATCH)"; } else { string received = MD5Hash(bytes); string expected = "e6c6c2a83c5911df3aaec06408729201"; if (received != expected) { result = "ERROR: Integrity check failed (CHECKSUM EXPECTED: " + expected + " BUT GOT " + received + ")"; } else { result = "OK: Integrity check passed!"; } } } _log = result + "\n\n" + _log; } }
IEnumerator DemoHTTPS() { _test = "DemoHTTPS"; HTTPRequest request = new HTTPRequest(); request.SetURL("https://google.com"). AppendQueryParameter("q", "unity"); using (_client = new HTTPClient(request)) { yield return StartCoroutine(_client.WaitUntilDone()); DebugAll(_client); } }
public Proxy(Uri uri) { ApiMessageHandler apiMessageHandler = new ApiMessageHandler(new WebRequestHandler { UseCookies = false }); this._httpClient = new HTTPClient(uri, apiMessageHandler); }
IEnumerator DemoAcceptableStatusCodes() { _test = "DemoAcceptableStatusCodes"; HTTPRequest request = new HTTPRequest(); request.SetURL("http://google.com/nonexistent"). AppendQueryParameter("q", "unity"); HTTPResponseMemoryStreamHandler responseHandler = new HTTPResponseMemoryStreamHandler(); responseHandler.AddAcceptableStatusCodeRange(200, 299); using (_client = new HTTPClient(request, responseHandler)) { yield return StartCoroutine(_client.WaitUntilDone()); DebugAll(_client); } }
public ClientResult(HTTPClient HTTPClient, HTTPResponse HTTPResponse) { this.HTTPClient = HTTPClient; this.HTTPResponse = HTTPResponse; }
IEnumerator DemoErrorHandling() { _test = "DemoErrorHandling"; HTTPRequest request = new HTTPRequest(); request.SetURL("http://www.wikipeeeeeedia.com"); using (_client = new HTTPClient(request)) { yield return StartCoroutine(_client.WaitUntilDone()); DebugAll(_client); Error err = _client.Error; if (err != null) { _log += "\n\nIs Host Lookup Error? " + (err.IsKnownCode(Error.KnownCode.HostLookupError) ? "YES" : "NO"); } } }
IEnumerator StartDemo() { _initialTime = Time.realtimeSinceStartup; _log = ""; _curIndex = _demoIndex; yield return StartCoroutine(_demos[_demoIndex]()); if (_client != null) { _client.Dispose(); _client = null; } Next(); }
public static IHTTPClient Create(Uri serverUrl, HttpMessageHandler innerHandler = null) { IHTTPClient client = new HTTPClient(serverUrl); return ( client ); }
IEnumerator DemoCacheControl() { _test = "DemoCacheControl"; HTTPRequest request = new HTTPRequest(); request.SetURL("http://www.google.com"). AppendQueryParameter("q", "unity"); HTTPResponseMemoryStreamHandler responseHandler = new HTTPResponseMemoryStreamHandler(); responseHandler.SetCachePolicy(CachePolicy.ReloadIgnoringLocalAndRemoteCacheData); using (_client = new HTTPClient(request, responseHandler)) { yield return StartCoroutine(_client.WaitUntilDone()); DebugAll(_client); } }
/// <summary> /// 异步上传共享文件夹 /// </summary> /// <param name="targetIPEndPoint">服务器IPEndPoint</param> /// <param name="csIPEndPoint">Client-Side Server 监听的IPEndPoint</param> /* *<?XML version = "1.0"? /> <Info> <ShareFiles> <File FileName="c#" Hash="888" Size="888"> </File> <File FileName="C++" Hash="999" Size="999"> </File> </ShareFiles> <Client Port=""> </Client> </Info> * */ public void UploadShareDirAsync(IPEndPoint targetIPEndPoint, IPEndPoint csIPEndPoint) { XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes")); XElement info = new XElement("Info"); XElement shareFiles = new XElement("ShareFiles"); foreach (KeyValuePair<string, string> dict in HPPClient.HashFullNameDict) { try { XElement file = new XElement("File"); FileInfo fi = new FileInfo(dict.Value); file.SetAttributeValue("FileName", fi.Name); file.SetAttributeValue("Hash", dict.Key); file.SetAttributeValue("Size", fi.Length); shareFiles.Add(file); } catch (Exception) { } } XElement client = new XElement("Client"); client.SetAttributeValue("Port", csIPEndPoint.Port); info.Add(client); info.Add(shareFiles); doc.Add(info); string xmlStr = doc.Declaration.ToString() + doc.ToString(); HTTPClient httpClient = new HTTPClient(); httpClient.Encoding = Encoding.UTF8; string url = string.Format("http://{0}:{1}/", targetIPEndPoint.Address, targetIPEndPoint.Port); Uri uri = new Uri(url); httpClient.UploadStringAsync(uri, "POST", xmlStr); }
IEnumerator DemoFilePost() { _test = "DemoFilePost"; string srcPath = Application.temporaryCachePath; srcPath = System.IO.Path.Combine(srcPath, "data"); byte[] data = Encoding.UTF8.GetBytes("hello\nworld\n!!!"); using (FileStream stream = new FileStream(srcPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) { stream.Write(data, 0, data.Length); } HTTPRequest request = new HTTPRequest(); request.SetURL("http://www.hashemian.com/tools/form-post-tester.php/test123"). SetContentFromPath(srcPath, "application/octet-stream"). Post(); using (_client = new HTTPClient(request)) { yield return StartCoroutine(_client.WaitUntilDone()); DebugAll(_client); } }