/// <summary> /// Get the client guid from a connection request /// Returns an empty guid on failure /// </summary> public static Guid GetGuid(HTTP.Request request) { // TODO: make this id extraction more robust var query = request.URI.Query; if (!query.StartsWith("?id=", StringComparison.CurrentCulture)) { Logger.WriteLine("Invalid WebSockets URI: id is not set in query string", Logger.Severity.Error); return(Guid.Empty); } var id = query.Substring("?id=".Length); try { var bytes = Convert.FromBase64String(id); var length = bytes.Length; if (length != 16) { Logger.WriteLine("Invalid WebSockets URI: id is not 16 bytes, got " + length + " bytes: " + id, Logger.Severity.Error); return(Guid.Empty); } return(new Guid(bytes)); } catch (FormatException) { Logger.WriteLine("Invalid WebSockets URI: id is not a valid 16 byte Guid", Logger.Severity.Error); return(Guid.Empty); } }
public Request(Method method, string route) { this.method = method; this.route = route; url = Sdk.url + route; request = new HTTP.Request(GetMethodString(), url); }
private IEnumerator Send() { EB.Debug.Log("Downloading asset bundle {0} from {1}", mName, mUrl); if (mLocal) { mWebRequest = UnityWebRequest.Get(mUrl); yield return(mWebRequest.SendWebRequest()); mDone = true; if (mWebRequest.isHttpError || mWebRequest.isNetworkError) { EB.Debug.LogWarning("Failed to download asset bundle {0} from {1}, error: {2}", mName, mUrl, mWebRequest.error); mError = mWebRequest.error; yield break; } else { mBytes = mWebRequest.downloadHandler.data; EB.Debug.Log("Downloaded asset bundle {0} from {1}, {2}", mName, mUrl, mWebRequest.downloadedBytes); } } else { mRquest = new HTTP.Request("GET", mUrl); mRquest.acceptGzip = false; mRquest.useCache = false; mRquest.maximumRedirects = 2; yield return(mRquest.Send()); mDone = true; if (mRquest.exception != null) { mError = mRquest.exception.Message; EB.Debug.LogWarning("Failed to download asset bundle {0} from {1}, error: {2}", mName, mUrl, mRquest.exception.Message); yield break; } else { if (mRquest.response.status != 200) { mError = "Not 200 status error(" + mRquest.response.status + ")"; EB.Debug.LogWarning("HTTP 404 error when download asset bundle {0} from {1}", mName, mUrl); yield break; } else { mBytes = mRquest.response.Bytes; EB.Debug.Log("Downloaded asset bundle {0} from {1}, {2}", mName, mUrl, mBytes.Length); } } } if (mBytes == null || mBytes.Length == 0) { mError = "Invalid response data"; EB.Debug.LogError("Downloaded asset bundle {0} error, invalid response data", mName); } }
public void Update() { while (requests.Count > 0) { HTTP.Request request = (Request)requests.Dequeue(); request.completedCallback(request); } }
/** * GET with plain request as callback */ public void GET(string endPoint, GETCallback cb) { HTTP.Request req = new HTTP.Request( "get", this.baseURL + endPoint ); // Add headers foreach (DictionaryEntry h in headers) { req.AddHeader((string) h.Key, (string) h.Value); } req.Send( ( request ) => { cb(request); }); }
static StackObject *get_response_1(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); HTTP.Request instance_of_this_method = (HTTP.Request) typeof(HTTP.Request).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.response; return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
/** * GET with result parsed as list */ public void GET(string endPoint, GETListCallback cb) { HTTP.Request req = new HTTP.Request( "get", this.baseURL + endPoint ); // Add headers foreach (DictionaryEntry h in headers) { req.AddHeader((string) h.Key, (string) h.Value); } req.Send( ( request ) => { var resList = Json.Deserialize(request.response.Text) as List<object>; cb(resList); }); }
void BoardSetup() { Hashtable data = new Hashtable(); data.Add("username", SystemInfo.deviceUniqueIdentifier); string strHostName = Dns.GetHostName(); IPHostEntry ipEntry = Dns.GetHostEntry(strHostName); IPAddress[] addr = ipEntry.AddressList; data.Add("ip", addr[addr.Length - 1].ToString()); Debug.Log("Send:"); foreach (string str in data.Keys) { Debug.Log(str + ": " + data[str]); } HTTP.Request req = new HTTP.Request("post", "http://143.248.139.70:8000/login", data); req.Send((request) => { Hashtable result = request.response.Object; Debug.Log("Result"); foreach (string str in result.Keys) { Debug.Log(str + ": " + result[str]); if ((string)(result[str].ToString()) == "System.Collections.Hashtable") { Hashtable rr = result[str] as Hashtable; foreach (string strstr in rr.Keys) { Debug.Log(strstr + ": " + rr[strstr]); } } } if (result == null) { Debug.LogWarning("Could not parse JSON response!"); return; } else { // Receive String from server and generate room Hashtable hashmap = (Hashtable)JSON.JsonDecode(request.response.Text); generateMapAndPlayer(hashmap, PlayerSpawnDir.SPAWN_NONE); } }); }
IEnumerator _InnerLoadRemoteImage() { while (LoadingList.Count > 0) { var data = LoadingList.Dequeue(); Texture2D t; if (textureCache.TryGetValue(data.Key, out t)) { if (data.Value != null) { data.Value.SetTexture(t); } continue; } int retries = 0; while (retries < 3) { HTTP.Request req = new HTTP.Request("GET", data.Key); yield return(req.Send()); if (req.exception != null) { retries++; yield return(new WaitForSecondsRealtime(0.5f)); continue; } Texture2D texture = new Texture2D(1, 1, TextureFormat.RGBA32, false); texture.LoadImage(req.response.Bytes); textureCache.Add(data.Key, texture); if (data.Value != null) { data.Value.SetTexture(texture); } break; } if (retries >= 3) { EB.Debug.LogError("Cannot load remote image: {0}", data.Key); } } RemoteLoadingCoroutine = null; }
/// <summary> /// Get the client name from a connection request /// </summary> public static string GetClientName(HTTP.Request request) { string name = string.Empty; var query = request.URI.Query; // TODO: make this name extraction more robust if (query.StartsWith("?name=", StringComparison.CurrentCulture)) { name = query.Substring("?name=".Length); } else if (request.Headers.ContainsKey("origin")) { name = request.Headers ["origin"].First(); } return(Uri.UnescapeDataString(name)); }
public void Download(string filename, string url) { var req = new HTTP.Request("HEAD", url); req.Send(delegate(Request headreq) { if (headreq.exception == null) { if (headreq.response.status == 200) { Debug.Log(headreq.response.headers.Get("Content-Length")); } } else { Debug.Log(headreq.exception); } }); }
static StackObject *Ctor_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.String @uri = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.String @method = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = new HTTP.Request(@method, @uri); return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
static Request CreateFromTopLine(string host, string top) { var parts = top.Split(' '); if (parts.Length != 3) { return(null); } if (parts [2] != "HTTP/1.1") { return(null); } var request = new HTTP.Request(); request.method = parts [0].ToUpper(); request.uri = new Uri(host + parts [1]); request.response = new Response(request); return(request); }
public void Dispose() { if (mDecompressDone.HasValue && !mDecompressDone.Value) { // how to stop? } mBytes = null; if (mWebRequest != null) { mWebRequest.Dispose(); mWebRequest = null; } if (mRquest != null) { mRquest = null; } }
protected static IEnumerator DownloadFromUrl(Collection <TRecordType> collection, string url) { var request = new HTTP.Request("GET", url, true); var icollection = collection as ICollection; request.Send(); yield return(request.Wait()); // Deserialize the collection var result = request.response.Text.Deserialize <Collection <TRecordType> > (); // Iterate through and update from the result. Remove old stuff foreach (var kv in result) { if (collection.Contains(kv)) { icollection.Changed(kv._id, null, kv.Coerce <Hashtable> ()); } } }
static IEnumerator SendBugReport(string crash) { if (Application.isEditor) { yield break; } var bytes = Encoding.GetBytes(crash); if (_url.StartsWith("http://")) { //Dictionary<string, string> headers = new Dictionary<string, string>(); //headers.Add("Content-Type", "application/json"); UnityWebRequest uwr = new UnityWebRequest(_url, UnityWebRequest.kHttpVerbPOST); uwr.uploadHandler = new UploadHandlerRaw(bytes); uwr.downloadHandler = new DownloadHandlerBuffer(); uwr.SetRequestHeader("Content-Type", "application/json"); //var www = new WWW( _url, bytes, headers ); yield return(uwr.SendWebRequest()); if (uwr.isHttpError || uwr.isNetworkError) { UnityEngine.Debug.LogWarning(uwr.error); } } else { HTTP.Request r = new HTTP.Request("POST", _url, bytes); r.headers.Add("Content-Type", "application/json"); yield return(r.Send()); if (r.exception != null) { UnityEngine.Debug.LogWarning(r.exception.Message); } } }
private static IEnumerator GetRequest(string url, System.Action <bool, string> callback) { var webService = new HTTP.Request("GET", url); yield return(webService.Send()); if (webService.exception != null) { Debug.Log(webService.exception); if (callback != null) { callback(false, webService.exception.Message); } } else { if (callback != null) { callback(true, webService.response.Text); } } }
public static void Upload(ContentMoment moment) { WWWForm form = moment.ToWWWForm(); HTTP.Request postRequest = new HTTP.Request("post", GetUrl("/moments"), form); postRequest.AddHeader("Authorization", accessToken); postRequest.Send((request) => { bool result = false; try { Hashtable thing = (Hashtable)JSON.JsonDecode(request.response.Text, ref result); } catch (NullReferenceException e) { Debug.Log(e.ToString()); return; } if (!result) { Debug.LogWarning("There is something wrong"); return; } Debug.Log("Moment uploaded"); }); }
private static HTTP.Response GetResponse(HTTP.Request inReq) { HTTP.Response outResp = new HTTP.Response(); switch (inReq.Uri) { case "/gamepad/shardlist": case "/gamepad/shardlist/": outResp.Content = Encoding.ASCII.GetBytes("{\"shards\":[{\"region\":1,\"isup\":true,\"timezone\":-600,\"weight\":100,\"host\":\"localhost:8995:1\",\"focusid\":0,\"name\":\"Emulator Nexus - Test Shard #1 (Port 8995)\",\"queuewait\":0,\"loadlevel\":0,\"language\":\"en\"},{\"region\":2,\"isup\":false,\"timezone\":-600,\"weight\":200,\"host\":\"localhost:7979:2\",\"focusid\":0,\"name\":\"Emulator Nexus - Test Shard #2 (Port 7979)\",\"queuewait\":0,\"loadlevel\":0,\"language\":\"en\"}],\"environmentDisabled\":0,\"accountRegion\":1}"); outResp.Code = "200 OK"; break; case "/gamepad/lastshard": case "/gamepad/lastshard/": outResp.Code = "200 OK"; break; default: break; } return(outResp); }
//cacheKey 需要缓存传对应URL 默认为空 private static void GetData(string cacheKey, string url, JsonData para, Action <string, bool> callback, bool encrypt) { if (cacheKey != null) { if (!Cache.CanUpdate(cacheKey) && Cache.getResult(cacheKey) != null) { callback(Cache.getResult(cacheKey).ResponseText, true); return; } } if (para == null) { para = new JsonData(); } url = GetURL(url, para, encrypt); HTTP.Request someRequest = new HTTP.Request("get", url); someRequest.Send(delegate(HTTP.Request req) { if (callback != null) { if (req.response != null) { callback(new MyHttpResult(req.response.bytes, req.response.status).ResponseText, req.response.status == 200); if (cacheKey != null) { Cache.UpdateRequestCache(cacheKey, new MyHttpResult(req.response.bytes, req.response.status)); } } else { callback(new MyHttpResult(null, -1).ResponseText, false); } } }); }
static void ReadCallback(IAsyncResult ar) { HUBHelper rHelper = (HUBHelper)ar.AsyncState; int byteCount = -1; try { byteCount = rHelper.stream.EndRead(ar); byte[] tempBuff = new byte[8192]; if (byteCount == 1) { byteCount += rHelper.stream.Read(rHelper.buffer, 1, rHelper.buffer.Length - 1); } HUBHelper helper = new HUBHelper(); helper.stream = rHelper.stream; rHelper.stream.BeginRead(helper.buffer, 0, 8192, new AsyncCallback(ReadCallback), helper); if (byteCount > 0) { HTTP.Request inReq = HTTP.ParseRequest(rHelper.buffer, byteCount); Log.Write(LogLevel.Debug, "New '{0}' request at '{1}'", inReq.Method, inReq.Uri); HTTP.Response outResp = GetResponse(inReq); rHelper.stream.Write(outResp.Construct()); } } catch (Exception e) { HandleDisconnect(rHelper); //Log.Write(LogLevel.Error, "{0}", e); } }
static Request CreateFromTopLine(string host, string top) { var parts = top.Split (' '); if (parts.Length != 3) return null; if (parts [2] != "HTTP/1.1") return null; var request = new HTTP.Request (); request.method = parts [0].ToUpper (); request.uri = new Uri (host + parts [1]); request.response = new Response(request); return request; }
private void ParseInput() { int pos; string temp; bool skip = false; while (bufferpos < buffer.Length - 1 && state != ParseState.Done && !skip) { switch (state) { case ParseState.Start: if ((pos = buffer.IndexOf("\r\n", bufferpos)) >= 0) { temp = buffer.Substring(bufferpos, pos - bufferpos); bufferpos = pos + 2; string[] parts = temp.Split(' '); if (parts.Length == 3) { request = new HTTP.Request(); request.Method = parts[0]; request.Url = parts[1]; request.Version = parts[2]; state = ParseState.Headers; } else { CleanUp(); } } break; case ParseState.Headers: if ((pos = buffer.IndexOf("\r\n", bufferpos)) >= 0) { temp = buffer.Substring(bufferpos, pos - bufferpos); bufferpos = pos + 2; if (temp.Length > 0) { string[] parts = temp.Split(new string[1] { ": " }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 2) { request.Headers.Add(parts[0], parts[1]); } } else { if (request.HasContent()) { state = ParseState.Content; } else { state = ParseState.Done; } } } break; case ParseState.Content: if (bufferpos + request.ContentLength <= buffer.Length) { int t = bufferpos + request.ContentLength - 1; request.Body = buffer.Substring(bufferpos, request.ContentLength); bufferpos += request.ContentLength; state = ParseState.Done; } else { skip = true; } break; } } if (state == ParseState.Done) { state = ParseState.Start; string toId = null, id = null, command = null; try { string[] array = request.Body.Split('|'); id = array[0]; toId = array[1]; command = array[2]; } catch (Exception e) { CleanUp(); request = null; return; } if (toId.Equals("no")) { // this is a query then register if (SIServer.dic.ContainsKey(id)) { Client client = SIServer.dic[id]; if (client.IsLive) client.CleanUp(); } SIServer.dic[id] = this; } else { // this is a send bool send = false; if (SIServer.dic.ContainsKey(toId)) { Client client = SIServer.dic[toId]; if (client.IsLive) { Response.GetHtmlResponse(id + '|' + command).SendResponse(client.stream, client); client.CleanUp(); SIServer.dic.TryRemove(toId, out client); Response.GetHtmlResponse("sent").SendResponse(stream, this); send = true; } } if (!send) { Response.GetHtmlResponse("fail").SendResponse(stream, this); } CleanUp(); } request = null; } }
private void ParseInput() { int pos; string temp; bool skip = false; while (bufferpos < buffer.Length - 1 && state != ParseState.Done && !skip) { switch (state) { case ParseState.Start: if ((pos = buffer.IndexOf("\r\n", bufferpos)) >= 0) { temp = buffer.Substring(bufferpos, pos - bufferpos); bufferpos = pos + 2; string[] parts = temp.Split(' '); if (parts.Length == 3) { request = new HTTP.Request(); request.Method = parts[0]; request.Url = parts[1]; request.Version = parts[2]; state = ParseState.Headers; } else { CleanUp(); } } break; case ParseState.Headers: if ((pos = buffer.IndexOf("\r\n", bufferpos)) >= 0) { temp = buffer.Substring(bufferpos, pos - bufferpos); bufferpos = pos + 2; if (temp.Length > 0) { string[] parts = temp.Split(new string[1] { ": " }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 2) { request.Headers.Add(parts[0], parts[1]); } } else { if (request.HasContent()) { state = ParseState.Content; } else { state = ParseState.Done; } } } break; case ParseState.Content: if (bufferpos + request.ContentLength <= buffer.Length) { int t = bufferpos + request.ContentLength - 1; request.Body = buffer.Substring(bufferpos, request.ContentLength); bufferpos += request.ContentLength; state = ParseState.Done; } else { skip = true; } break; } } if (state == ParseState.Done) { state = ParseState.Start; HTTP.Response response; if (request.VerifyAuth(authconfig)) { response = server.HandleRequest(request); } else { response = Response.Get401Response(authconfig); } response.SendResponse(stream, this); request = null; } }
public bool sendSignedRequest(List <string> paramArray, string postBody, ref JSONNode jsonRes) { TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1)); string timestamp = t.ToString(); List <string> parameters = (paramArray != null) ? paramArray : new List <string>(); parameters.Add("key=" + m_Key); parameters.Add("timestamp=" + timestamp); string url_params = String.Join("&", parameters.ToArray()); string url = m_url + "?" + url_params; Debug.Log("Signed url request: " + url); List <string> headers = new List <string>(); headers.Add("Host: " + ApiUtil.API_HOST); headers.Add("Content-type: application/json"); headers.Add("User-Agent: Unity Knetik SDK"); HTTP.Request theRequest; if (postBody != null) { System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); headers.Add("Content-Length: " + postBody.Length); data = encoding.GetBytes(postBody); theRequest = new HTTP.Request((m_method != null) ? m_method : "post", url, data); theRequest.AddHeader("Signature", signRequest(m_url, parameters, headers, postBody)); //theRequest.AddHeader("Content-length", postBody.Length.ToString()); } else { theRequest = new HTTP.Request((m_method != null) ? m_method : "get", url); theRequest.AddHeader("Signature", signRequest(m_url, parameters, headers, null)); } theRequest.AddHeader("Content-type", "application/json"); //theRequest.AddHeader("connection", "Close"); theRequest.AddHeader("User-Agent", "Unity Knetik SDK"); theRequest.synchronous = true; theRequest.Send(); string strResp = theRequest.response.Text; Debug.Log("Response: (" + theRequest.response.status + "): " + strResp); if (theRequest.response.status != 200) { return(false); } try { jsonRes = JSON.Parse(strResp); if (jsonRes == null) { Debug.Log("json parse failed"); return(false); } } catch (Exception e) { Debug.Log("Json parse Exception: " + e); return(false); } if (jsonRes["error"] == null) { Debug.Log("No error node!"); return(false); } JSONNode error = jsonRes["error"]; if ((error["success"] == null) || (error["success"].AsBool == false)) { Debug.Log("json success is false"); m_errorMsg = error["message"].Value; return(false); } return(true); }
public void SetBody(WWWForm form) { request = new HTTP.Request(GetMethodString(), url, form); }
public void EndHeaders() { // Now that headers are over, all reading should be manual Autoread = false; // Prep the request DataAdapter = new Core.RequestDataAdapter(async delegate { await ReadAsync(); }); Request = new HTTP.Request(DataAdapter); Request.Headers = Headers; Request.Method = Method; Request.Protocol = Protocol; // Parse out the URI, which ends up being more annoying than it // should be. Stay tuned... var uri = new Uri(Path, UriKind.RelativeOrAbsolute); // Set the path if (uri.IsAbsoluteUri) Request.Path = uri.AbsolutePath; else Request.Path = Path.Split('?')[0]; // Set the host string temp; if (Headers.TryGetValue("host", out temp)) Request.Host = temp; else if (uri.IsAbsoluteUri) Request.Host = uri.Host; else Request.Host = null; // Set the query if (uri.IsAbsoluteUri) { Request.Query = Util.FormUrlEncoding.Parse(uri.Query.Length > 0 ? uri.Query.Substring(1) : ""); } else { var split = Path.Split(QuerySep, 2); Request.Query = Util.FormUrlEncoding.Parse(split.Length > 1 ? split[1] : ""); } // Build the response bool keepAlive = Version == HTTP.Version.HTTP1_1; if (Headers.TryGetValue("connection", out temp)) { temp = temp.ToLower(); if (temp == "close") keepAlive = false; else if (temp == "keep-alive") keepAlive = true; } Response = new HTTP.Response(Version, this, keepAlive, delegate(bool forceDisconnect) { // Now that we're done, we should kill the client if // either the request expects it, or the response // requires it. if (forceDisconnect || !keepAlive) Kill(); else Start(); }); // Since we've set up the request, it'll get scheduled at the END of the current // read call. This prevents issues with overlapping reads, because reads are // guaranteed to have finished before we run any response logic. }
public void gotoNextStage(Player.Direction dir) { switch (dir) { case Player.Direction.EAST: nextSpawnDir = PlayerSpawnDir.SPAWN_WEST; break; case Player.Direction.WEST: nextSpawnDir = PlayerSpawnDir.SPAWN_EAST; break; case Player.Direction.SOUTH: nextSpawnDir = PlayerSpawnDir.SPAWN_NORTH; break; case Player.Direction.NORTH: nextSpawnDir = PlayerSpawnDir.SPAWN_SOUTH; break; } Hashtable data = new Hashtable(); data.Add("entrance", ((int)dir).ToString()); data.Add("hash", currentStageHash); data.Add("username", SystemInfo.deviceUniqueIdentifier); string strHostName = Dns.GetHostName(); IPHostEntry ipEntry = Dns.GetHostEntry(strHostName); IPAddress[] addr = ipEntry.AddressList; data.Add("ip", addr[addr.Length - 1].ToString()); Debug.Log("Send:"); foreach (string str in data.Keys) { Debug.Log(str + ": " + data[str]); } HTTP.Request req = new HTTP.Request("post", "http://143.248.139.70:8000/randomMapGenerator", data); req.Send((request) => { Hashtable result = request.response.Object; Debug.Log("Result"); foreach (string str in result.Keys) { Debug.Log(str + ": " + result[str]); if ((string)(result[str].ToString()) == "System.Collections.Hashtable") { Hashtable rr = result[str] as Hashtable; foreach (string strstr in rr.Keys) { Debug.Log(strstr + ": " + rr[strstr]); } } } if (result == null) { Debug.LogWarning("Could not parse JSON response!"); return; } else { // Receive String from server and generate room Hashtable hashmap = (Hashtable)JSON.JsonDecode(request.response.Text); BoardHolderClear(); BoardHolderInit(); generateMapAndPlayer(hashmap, nextSpawnDir); } }); }
public void Start() { // Set up the state Ready = true; Autoread = true; Request = null; Response = null; Version = HTTP.Version.HTTP1_0; Method = null; Path = null; Headers = null; DataAdapter = null; // If there's already a reader chugging away, simply setting // autoread will take care of it. Otherwise, we need to restart // the reading. Read(); }
private void performRequest(string method, Hashtable parameters = null, Action<RestifizerResponse> callback = null) { HTTP.Request someRequest; string url = Path; string queryStr = ""; // paging if (PageNumber != -1) { if (queryStr.Length > 0) { queryStr += "&"; } queryStr += "per_page=" + PageNumber; } if (PageSize != -1) { if (queryStr.Length > 0) { queryStr += "&"; } queryStr += "page=" + PageSize; } // filtering if (filterParams != null && filterParams.Count > 0) { if (queryStr.Length > 0) { queryStr += "&"; } string filterValue = JSON.JsonEncode(filterParams); queryStr += "filter=" + filterValue; } // extra params if (extraQuery != null && extraQuery.Count > 0) { foreach (string key in extraQuery.Keys) { if (queryStr.Length > 0) { queryStr += "&"; } queryStr += key + "=" + extraQuery[key]; } } if (queryStr.Length > 0) { url += "?" + queryStr; } // Handle authentication if (this.authType == AuthType.Client) { if (parameters == null) { parameters = new Hashtable(); } parameters.Add( "client_id", restifizerParams.GetClientId() ); parameters.Add( "client_secret", restifizerParams.GetClientSecret() ); someRequest = new HTTP.Request(method, url, parameters); } else if (this.authType == AuthType.Bearer) { if (parameters == null) { someRequest = new HTTP.Request(method, url); } else { someRequest = new HTTP.Request(method, url, parameters); } someRequest.SetHeader("Authorization", "Bearer " + restifizerParams.GetAccessToken()); } else { if (parameters == null) { someRequest = new HTTP.Request(method, url); } else { someRequest = new HTTP.Request(method, url, parameters); } } string tag = this.Tag; // Perform request someRequest.Send( ( request ) => { if (request.response == null) { RestifizerError error = RestifizerErrorFactory.Create(-1, null, tag); if (errorHandler != null) { bool propagateResult = !errorHandler.onRestifizerError(error); if (propagateResult) { callback(null); } } else { callback(null); } return; } bool result = false; object responseResult = JSON.JsonDecode(request.response.Text, ref result); if (!result) { RestifizerError error = RestifizerErrorFactory.Create(-2, request.response.Text, tag); if (errorHandler != null) { bool propagateResult = !errorHandler.onRestifizerError(error); if (propagateResult) { callback(null); } } else { callback(null); } return; } bool hasError = request.response.status >= 300; if (hasError) { RestifizerError error = RestifizerErrorFactory.Create(request.response.status, responseResult, tag); if (errorHandler != null) { bool propagateResult = !errorHandler.onRestifizerError(error); if (propagateResult) { callback(new RestifizerResponse(request, error, tag)); } } else { callback(new RestifizerResponse(request, error, tag)); } } else if (responseResult is ArrayList) { callback(new RestifizerResponse(request, (ArrayList)responseResult, tag)); } else if (responseResult is Hashtable) { callback(new RestifizerResponse(request, (Hashtable)responseResult, tag)); } else { Debug.LogWarning("Unsupported type in response: " + responseResult.GetType()); callback(null); } }); }
/// <summary> /// Send request to the API with the given HTTP Method, path and data. The authentication key is /// automatically attached to appropriate requests. /// </summary> /// <param name="routeName">Route name.</param> /// <param name="callback">Callback.</param> public void Request(string routeName, Dictionary<string, string> replacements, WWWForm data, Complete callback, Error errorCallback) { Route route = this.Routes [routeName]; // Add key to all requests, if we have it if (null != this.ApiKey && null != this.ApiSecret && route.IsSigned) { SignRequest (route.Path, ref data); } string path = route.Path; foreach (KeyValuePair<string, string> replacement in replacements) { path = path.Replace (replacement.Key, WWW.EscapeURL (replacement.Value)); } HTTP.Request rq = new HTTP.Request (route.Method.ToString(), HttpEndpoint + path, data); rq.synchronous = !route.IsAsync; rq.useCache = false; GetResponse (rq, callback, errorCallback); }
/** * POST with result parsed as Dictionary<string,object> */ public void POST(string endPoint, Hashtable body, GETDictCallback cb) { Console.WriteLine(this.baseURL + endPoint); HTTP.Request req = new HTTP.Request( "post", this.baseURL + endPoint, body ); // Add headers foreach (DictionaryEntry h in headers) { req.AddHeader((string) h.Key, (string) h.Value); } req.Send( ( request ) => { var resObj = Json.Deserialize(request.response.Text) as Dictionary<string, object>; cb(resObj); }); }
IEnumerator _GetRemoteBundlesInfoFileCoroutine(string url, System.Action <bool> action, GameObject target) { #if USE_LOCAL_ABINFO //使用本地AB依赖包的配制信息表 string textPath = "BundleShipInfo"; TextAsset textAsset = Resources.Load <TextAsset>(textPath); if (textAsset == null) { EB.Debug.LogErrorFormat("使用读取本地依赖AB包信息表,发现指定不存在相应的文件textPath:{0}", textPath); yield break; } else { EB.Debug.LogFormat("使用本地AB依赖包的配制信息表,相应的文件textPath:{0}", textPath); } ParseRemoteBundlesInfoFile(textAsset.text); isReady = true; isGetting = false; AssetUtils.DoAction(action, true, target); yield break; #endif yield return(null); if (!AssetUtils.LoadFromLocalFile(url)) { HTTP.Request r = new HTTP.Request("GET", url); r.acceptGzip = true; r.useCache = false; r.maximumRedirects = 2; EB.Debug.Log("Getting Remote Bundles Info File from: {0}", url); yield return(r.Send()); if (r.exception != null) { isReady = false; isGetting = false; EB.Debug.LogWarning("CAN NOT fetch scene description file from {0}, error = {1}", url, r.exception.Message); AssetUtils.DoAction(action, false, target); } else { if (r.response.status == 404) { EB.Debug.LogError("HTTP 404 error when gettings file from url: {0}", url); } else { EB.Debug.Log("_GetRemoteBundlesInfoFileCoroutine: success, length = {0}", r.response.Text.Length); #if UNITY_EDITOR || UNITY_IOS byte[] data = r.response.Bytes; ParseRemoteBundlesInfoFile(data); #else string data = r.response.Text; ParseRemoteBundlesInfoFile(data); #endif GM.AssetManager.ResetDownloaBundleSize(); isReady = true; isGetting = false; if (data != null) { int gid = System.GC.GetGeneration(data); data = null; System.GC.Collect(gid); } AssetUtils.DoAction(action, true, target); } } } else { UnityWebRequest request = UnityWebRequest.Get(url); EB.Debug.Log("Getting Remote Bundles Info File from: {0}", url); yield return(request.SendWebRequest()); if (request.isHttpError || request.isNetworkError) { isReady = false; isGetting = false; EB.Debug.LogError("CAN NOT fetch scene description file from {0}, error = {1}", url, request.error); AssetUtils.DoAction(action, false, target); } else { //EB.Debug.Log("_GetRemoteBundlesInfoFileCoroutine: success, length = {0}", request.downloadHandler.text.Length); #if UNITY_EDITOR || UNITY_IOS byte[] data = request.downloadHandler.data; ParseRemoteBundlesInfoFile(data); #else string data = request.downloadHandler.text; ParseRemoteBundlesInfoFile(data); #endif GM.AssetManager.ResetDownloaBundleSize(); isReady = true; isGetting = false; if (data != null) { int gid = System.GC.GetGeneration(data); data = null; System.GC.Collect(gid); } AssetUtils.DoAction(action, true, target); } request.Dispose(); request = null; yield return(true); } }
public void SendPackage(PackageOut pkg) { var r = new HTTP.Request("GET", _url, pkg.ToByteArray()); r.Send(_OnResponse); Log.Debug("Socket SendPackage: [" + pkg.code.ToString() + "," + BitConverter.ToString(pkg.GetByteArray(0, pkg.length)) + "]"); }
public static IEnumerator PostImageTweet(string text, byte[] image, string consumerKey, string consumerSecret, AccessTokenResponse response, PostTweetCallback callback) { if (string.IsNullOrEmpty(text) || text.Length > 140) { Debug.Log(string.Format("PostTweet - text[{0}] is empty or too long.", text)); callback(false); } else if (image == null || image.Length == 0) { Debug.Log("Missing image."); callback(false); } else { Dictionary<string, string> parameters = new Dictionary<string, string>(); var form = new WWWForm(); form.AddBinaryData("status", UTF8Encoding.UTF8.GetBytes(text)); form.AddBinaryData("media[]", image, "anuki.jpg", "application/octet-stream"); var request = new HTTP.Request(PostImageTweetURL, form); request.headers.Add("Authorization", GetHeaderWithAccessToken("POST", PostImageTweetURL, consumerKey, consumerSecret, response, parameters)); yield return request.Send(); if (request.exception != null) { Debug.Log(string.Format("PostImageTweet - failed:\n" + request.exception.Message)); callback(false); } else { var txt = request.response.Text; if (txt.Contains("\"errors\":")) { Debug.Log(string.Format("PostImageTweet - failed. {0}", txt)); callback(false); } else { Debug.Log("Response: " + txt); callback(true); } } } }
void EndRead(IAsyncResult result) { int bytes = 0; try { bytes = ClientStream.EndRead(result); } catch (IOException err) { Kill(); return; } // If we were disposed while waiting for a read to go through, then something else // killed the request/response and we don't have to do anything. catch (ObjectDisposedException) { return; } // If we read no bytes, then the client disconnected and we should cancel // the request and response. if (bytes == 0) { Kill(); } // Otherwise, parse the data out else { // Continue to fill up the old buffer if we haven't used the whole of it. Do // this BEFORE shooting the bytes through the parser to ensure that if another // Read is queued, it will have the correct offset. var origOffset = Offset; var origBuffer = Buffer; if (BUFFER_SIZE - Offset > bytes) { Offset += bytes; } else { Buffer = new byte[BUFFER_SIZE]; Offset = 0; } Parser.AddBytes(new ArraySegment<byte>(origBuffer, origOffset, bytes)); // If, once we're done parsing, we have a response ready to fire off, do it if (Request != null) { // Hold on to these, because they'll get cleared var req = Request; var res = Response; // Clear out request to prevent it from being queued again. Request = null; // Execute the response Scheduler(async delegate { // Need to wrap this initial call in a try so that // we can handle errors by killing the connection. try { var action = Router.Resolve(req); if (action != null) { await action(req, res); } else { await WriteError(404, "Page Not Found").ContinueWith(delegate(Task t) { if (t.IsCanceled || t.IsFaulted) { Kill(); } else { Start(); } }); } } catch (Exception) { Kill(); throw; } }); } // If we still need to keep reading automatically, do that if (Autoread) Read(); } }
private void performRequest(string method, Hashtable parameters = null, Action <RestifizerResponse> callback = null) { HTTP.Request someRequest; string url = Path; string queryStr = ""; // paging if (PageNumber != -1) { if (queryStr.Length > 0) { queryStr += "&"; } queryStr += "per_page=" + PageNumber; } if (PageSize != -1) { if (queryStr.Length > 0) { queryStr += "&"; } queryStr += "page=" + PageSize; } // filtering if (filterParams != null && filterParams.Count > 0) { if (queryStr.Length > 0) { queryStr += "&"; } string filterValue = JSON.JsonEncode(filterParams); queryStr += "filter=" + filterValue; } // extra params if (extraQuery != null && extraQuery.Count > 0) { foreach (string key in extraQuery.Keys) { if (queryStr.Length > 0) { queryStr += "&"; } queryStr += key + "=" + extraQuery[key]; } } if (queryStr.Length > 0) { url += "?" + queryStr; } // Handle authentication if (this.authType == AuthType.Client) { if (parameters == null) { parameters = new Hashtable(); } parameters.Add("client_id", restifizerParams.GetClientId()); parameters.Add("client_secret", restifizerParams.GetClientSecret()); someRequest = new HTTP.Request(method, url, parameters); } else if (this.authType == AuthType.Bearer) { if (parameters == null) { someRequest = new HTTP.Request(method, url); } else { someRequest = new HTTP.Request(method, url, parameters); } someRequest.SetHeader("Access-Token", restifizerParams.GetAccessToken()); } else { if (parameters == null) { someRequest = new HTTP.Request(method, url); } else { someRequest = new HTTP.Request(method, url, parameters); } } // Set Request Keys someRequest.SetHeader(SConstants.RequestTokenKey, restifizerParams.GetRequestKey()); string tag = this.Tag; // Perform request someRequest.Send((request) => { if (request.response == null) { RestifizerError error = RestifizerErrorFactory.Create(-1, null, tag); if (errorHandler != null) { bool propagateResult = !errorHandler.onRestifizerError(error); if (propagateResult) { callback(null); } } else { callback(null); } return; } bool result = false; Debug.Log("Response Text: " + request.response.Text); object responseResult = JSON.JsonDecode(request.response.Text, ref result); if (!result) { RestifizerError error = RestifizerErrorFactory.Create(-2, request.response.Text, tag); if (errorHandler != null) { bool propagateResult = !errorHandler.onRestifizerError(error); if (propagateResult) { callback(null); } } else { callback(null); } return; } bool hasError = request.response.status >= 300; if (hasError) { RestifizerError error = RestifizerErrorFactory.Create(request.response.status, responseResult, tag); if (errorHandler != null) { bool propagateResult = !errorHandler.onRestifizerError(error); if (propagateResult) { callback(new RestifizerResponse(request, error, tag)); } } else { callback(new RestifizerResponse(request, error, tag)); } } else if (responseResult is ArrayList) { callback(new RestifizerResponse(request, (ArrayList)responseResult, tag)); } else if (responseResult is Hashtable) { callback(new RestifizerResponse(request, (Hashtable)responseResult, tag)); } else { Debug.LogWarning("Unsupported type in response: " + responseResult.GetType()); callback(null); } }); }
public bool sendApiRequest(string request_str, ref JSONNode jsonRes) { Debug.Log("Request = " + request_str); System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); data = encoding.GetBytes(request_str); Debug.Log("m_url = " + m_url); Debug.Log("data = " + data); HTTP.Request theRequest = new HTTP.Request("post", m_url, data); theRequest.AddHeader("Content-Type", "application/x-www-form-urlencoded"); theRequest.synchronous = true; theRequest.Send(); Debug.Log("theRequest = " + theRequest); if (theRequest.response == null) { Debug.Log("RESPONSE IS NULL!!!!"); return(false); } Debug.Log("theRequest.response = " + theRequest.response); string strResp = theRequest.response.Text; Debug.Log("Response: (" + theRequest.response.status + "): " + strResp); if (theRequest.response.status != 200) { return(false); } try { jsonRes = JSON.Parse(strResp); if (jsonRes == null) { Debug.Log("json parse failed"); return(false); } } catch (Exception e) { Debug.Log("Json parse Exception: " + e); return(false); } if (jsonRes["error"] == null) { Debug.Log("No error node!"); return(false); } JSONNode error = jsonRes["error"]; if ((error["success"] == null) || (error["success"].AsBool == false)) { Debug.Log("json success is false"); m_errorMsg = error["message"].Value; return(false); } return(true); }