// this builds a POST request, sends it, // awaits for a response, and then triggers // either onSuccess or onFail private static async void PostString(string uri, List <IMultipartFormSection> data = null, OnRestSuccess onSuccess = null, OnRestFail onFail = null, bool sendToken = true, string method = "POST") { if (sendToken && token.expires_in == 0) { return; // we lost the token } if (data == null) { data = MakePostData(); } byte[] boundary = UnityWebRequest.GenerateBoundary(); UnityWebRequest request = UnityWebRequest.Post(uri, data, boundary); request.method = method; if (sendToken) { request.SetRequestHeader("Authorization", $"Bearer {token.access_token}"); } UnityWebRequestAsyncOperation task = request.SendWebRequest(); while (!task.isDone) { await Task.Yield(); } RouteResponse(request, onSuccess, onFail); }
protected UnityWebRequest CreateMultipartUpload(UnityWebRequest webRequest) { // Can't use MultipartFormDataSection utils to build mutlipart body, // because Google has added strict requirements for the body format. // Issue: https://github.com/Elringus/UnityGoogleDrive/issues/30). var newLine = "\r\n"; var newLineDouble = newLine + newLine; var boundary = Encoding.ASCII.GetString(UnityWebRequest.GenerateBoundary()); var boundaryDelimeter = newLineDouble + "--" + boundary; var dataList = new List <byte>(); dataList.AddRange(Encoding.UTF8.GetBytes( boundaryDelimeter + newLine + "Content-Type: " + RequestContentType + newLineDouble + JsonUtils.ToJsonPrivateCamel(RequestData) + boundaryDelimeter + newLine + "Content-Type: " + DefaultMimeType + newLineDouble)); dataList.AddRange(RequestPayload); dataList.AddRange(Encoding.UTF8.GetBytes(newLine + "--" + boundary + "--")); webRequest.uploadHandler = new UploadHandlerRaw(dataList.ToArray()); webRequest.SetRequestHeader("Content-Type", string.Concat("multipart/related; boundary=", boundary)); return(webRequest); }
IEnumerator UploadJPGwithGPS(string filePath, string apiURL, float langitude, float latitude, Action <string> getJsonCameraObjects) { localizationStatus = LocalizationStatus.WaitForAPIAnswer; byte[] bytes = File.ReadAllBytes(filePath); Debug.Log("bytes = " + bytes.Length); List <IMultipartFormSection> form = new List <IMultipartFormSection>(); string jsona = "{\"gps\":{\"latitude\":" + langitude + ",\"longitude\":" + latitude + "},\"rotation\": 0,\"mirrored\": false}"; Debug.Log("" + jsona); form.Add(new MultipartFormFileSection("image", bytes, "test.jpg", "image/jpeg")); form.Add(new MultipartFormDataSection("description", jsona)); byte[] boundary = UnityWebRequest.GenerateBoundary(); var request = UnityWebRequest.Post(apiURL, form, boundary); request.SetRequestHeader("Accept-Encoding", "gzip, deflate, br"); request.SetRequestHeader("Accept", "application/vnd.myplace.v2+json"); Debug.Log("Uploading Screenshot started..."); yield return(request.SendWebRequest()); if (request.isNetworkError || request.isHttpError) { Debug.Log(request.error); localizationStatus = LocalizationStatus.ServerError; } else { Debug.Log("Finished Uploading Screenshot"); } Debug.Log(request.downloadHandler.text); getJsonCameraObjects(request.downloadHandler.text); }
// Make a POST request to the server for the visualiser file IEnumerator generateVisualiser() { //generate a unique boundary byte[] boundary = UnityWebRequest.GenerateBoundary(); List <IMultipartFormSection> formData = new List <IMultipartFormSection>(); formData.Add(new MultipartFormDataSection("domain", domaintxt)); formData.Add(new MultipartFormDataSection("problem", problemtxt)); formData.Add(new MultipartFormDataSection("animation", animationprofile)); formData.Add(new MultipartFormDataSection("plan", plantxt)); formData.Add(new MultipartFormDataSection("url", customSolverDomain)); //serialize form fields into byte[] => requires a bounday to put in between fields byte[] formSections = UnityWebRequest.SerializeFormSections(formData, boundary); //UnityWebRequest www = UnityWebRequest.Post("http://127.0.0.1:8000/upload/pddl", formData); //UnityWebRequest www = UnityWebRequest.Post("https://planning-visualisation-solver.herokuapp.com/upload/pddl", formData); UnityWebRequest www = UnityWebRequest.Post("/upload/pddl", formData); www.uploadHandler = new UploadHandlerRaw(formSections); www.SetRequestHeader("Content-Type", "multipart/form-data; boundary=" + Encoding.UTF8.GetString(boundary)); yield return(www.SendWebRequest()); // Showing error scene if plan are not found or experiencing network error if (www.isNetworkError || www.isHttpError) { SceneManager.LoadScene("NetworkError"); Debug.Log(www.error); } else { //Debug.Log("Form upload complete!"); Coordinator.PushParameters("Visualisation", www.downloadHandler.text); SceneManager.LoadScene("Visualisation"); } }
private IEnumerator MultiFormRequestAPIByPost(Action <string> _action, int _domainIndex, string _api, List <IMultipartFormSection> _data) { using (UnityWebRequest req = UnityWebRequest.Post(GetAPIUrl(_domainIndex, _api), _data)) { byte[] boundary = UnityWebRequest.GenerateBoundary(); byte[] formSections = UnityWebRequest.SerializeFormSections(_data, boundary); byte[] terminate = Encoding.UTF8.GetBytes(String.Concat("\r\n--", Encoding.UTF8.GetString(boundary))); byte[] body = new byte[formSections.Length + terminate.Length]; Buffer.BlockCopy(formSections, 0, body, 0, formSections.Length); Buffer.BlockCopy(terminate, 0, body, formSections.Length, terminate.Length); string contentType = String.Concat("multipart/form-data; boundary=", Encoding.UTF8.GetString(boundary)); req.uploadHandler = new UploadHandlerRaw(body); req.uploadHandler.contentType = contentType; req.timeout = timeout; yield return(req.SendWebRequest()); CallbackMessage(_action, req); } }
public MultipartBody () { boundary = UnityWebRequest.GenerateBoundary (); boundaryString = Encoding.UTF8.GetString (boundary); separator = string.Format ("\r\n--{0}\r\n", boundaryString); stream = new MemoryStream (); requestBody = new BinaryWriter (stream); }
private static string GetFormSectionsContentType(out byte[] bodyRaw, RequestHelper options) { byte[] boundary = UnityWebRequest.GenerateBoundary(); byte[] formSections = UnityWebRequest.SerializeFormSections(options.FormSections, boundary); byte[] terminate = Encoding.UTF8.GetBytes(string.Concat("\r\n--", Encoding.UTF8.GetString(boundary), "--")); bodyRaw = new byte[formSections.Length + terminate.Length]; System.Buffer.BlockCopy(formSections, 0, bodyRaw, 0, formSections.Length); System.Buffer.BlockCopy(terminate, 0, bodyRaw, formSections.Length, terminate.Length); return(string.Concat("multipart/form-data; boundary=", Encoding.UTF8.GetString(boundary))); }
public IEnumerator Upload2() { StreamReader reader = new StreamReader("Assets/Tests/output_log.txt"); string stringData = reader.ReadToEnd(); reader.Close(); //string url = "https://ktane.timwi.de/upload-log"; string url = "http://127.0.0.1:8080"; List <IMultipartFormSection> form = new List <IMultipartFormSection> { new MultipartFormFileSection("log", stringData, null, "output_log.txt") }; // generate a boundary then convert the form to byte[] byte[] boundary = UnityWebRequest.GenerateBoundary(); byte[] formSections = UnityWebRequest.SerializeFormSections(form, boundary); // my termination string consisting of CRLF--{boundary}-- byte[] terminate = Encoding.UTF8.GetBytes(String.Concat("\r\n--", Encoding.UTF8.GetString(boundary), "--")); // Make my complete body from the two byte arrays byte[] body = new byte[formSections.Length + terminate.Length]; Buffer.BlockCopy(formSections, 0, body, 0, formSections.Length); Buffer.BlockCopy(terminate, 0, body, formSections.Length, terminate.Length); // Set the content type - NO QUOTES around the boundary string contentType = String.Concat("multipart/form-data; boundary=", Encoding.UTF8.GetString(boundary)); // Make my request object and add the raw body. Set anything else you need here UnityWebRequest www = new UnityWebRequest(); UploadHandler uploader = new UploadHandlerRaw(body); uploader.contentType = contentType; www.uploadHandler = uploader; www.downloadHandler = new DownloadHandlerBuffer(); www.method = "POST"; www.url = url; yield return(www.Send()); if (www.isNetworkError || www.isHttpError) { Debug.Log("Error: " + www.error + " (" + www.responseCode + ")"); } else { string rawUrl = www.downloadHandler.text; Debug.Log("Response Text: " + rawUrl); } Debug.Log("Response Text: " + www.downloadHandler.text); yield break; }
/// <summary> /// Send the web request to the server /// </summary> /// <returns>An UnityWebRequestAsyncOperation object.</returns> /// <param name="request">An UnityWebRequest object.</param> /// <param name="options">An options object.</param> public static IEnumerator SendWebRequest(this UnityWebRequest request, RequestHelper options) { byte[] bodyRaw = null; string contentType = "application/json"; if (options.Body != null || !string.IsNullOrEmpty(options.BodyString)) { var bodyString = options.BodyString; if (options.Body != null) { bodyString = JsonUtility.ToJson(options.Body); } bodyRaw = Encoding.UTF8.GetBytes(bodyString.ToCharArray()); } else if (options.SimpleForm != null && options.SimpleForm.Count > 0) { bodyRaw = UnityWebRequest.SerializeSimpleForm(options.SimpleForm); contentType = "application/x-www-form-urlencoded"; } else if (options.FormSections != null && options.FormSections.Count > 0) { byte[] boundary = UnityWebRequest.GenerateBoundary(); byte[] formSections = UnityWebRequest.SerializeFormSections(options.FormSections, boundary); byte[] terminate = Encoding.UTF8.GetBytes(string.Concat("\r\n--", Encoding.UTF8.GetString(boundary), "--")); bodyRaw = new byte[formSections.Length + terminate.Length]; System.Buffer.BlockCopy(formSections, 0, bodyRaw, 0, formSections.Length); System.Buffer.BlockCopy(terminate, 0, bodyRaw, formSections.Length, terminate.Length); contentType = string.Concat("multipart/form-data; boundary=", Encoding.UTF8.GetString(boundary)); } if (bodyRaw != null) { request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw); request.uploadHandler.contentType = contentType; } request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", contentType); foreach (var header in RestClient.DefaultRequestHeaders) { request.SetRequestHeader(header.Key, header.Value); } foreach (var header in options.Headers) { request.SetRequestHeader(header.Key, header.Value); } if (options.Timeout.HasValue) { request.timeout = options.Timeout.Value; } if (options.ChunkedTransfer.HasValue) { request.chunkedTransfer = options.ChunkedTransfer.Value; } options.request = request; yield return(request.SendWebRequest()); }
private UnityWebRequest Post(string submissionUrl, List <IMultipartFormSection> formData) { var boundaryIdBytes = UnityWebRequest.GenerateBoundary(); var request = UnityWebRequest.Post(submissionUrl, formData, boundaryIdBytes); request.timeout = RequestTimeout; request.IgnoreSsl(IgnoreSslValidation); request.SetMultipartFormData(boundaryIdBytes); return(request); }
private IEnumerator UploadStory(string storyName) { string form = "{\"name\":\"" + storyName + ".story\"}"; UnityWebRequest signingRequest = new UnityWebRequest(SigningUrl, "POST") { uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(form)), downloadHandler = new DownloadHandlerBuffer() }; signingRequest.SetRequestHeader("Content-Type", "application/json"); yield return(signingRequest.SendWebRequest()); if (signingRequest.isNetworkError || signingRequest.isHttpError) { Debug.Log("error signing url " + signingRequest.error); } Debug.Log("post complete: " + signingRequest.downloadHandler.text); Debug.Log(signingRequest.downloadHandler.text); string uploadUrl = signingRequest.downloadHandler.text; var multipartForm = new List <IMultipartFormSection> { new MultipartFormFileSection("file", ReadAllBytes(BaseStoryPath(storyName) + ".story"), "terrain.terrain", "application/octet-stream") }; byte[] boundary = UnityWebRequest.GenerateBoundary(); byte[] formSections = UnityWebRequest.SerializeFormSections(multipartForm, boundary); ; byte[] terminate = Encoding.UTF8.GetBytes(String.Concat("\r\n--", Encoding.UTF8.GetString(boundary), "--")); byte[] body = new byte[formSections.Length + terminate.Length]; Buffer.BlockCopy(formSections, 0, body, 0, formSections.Length); Buffer.BlockCopy(terminate, 0, body, formSections.Length, terminate.Length); string contentType = String.Concat("multipart/form-data; boundary=", Encoding.UTF8.GetString(boundary)); UnityWebRequest wr = new UnityWebRequest(uploadUrl, "PUT"); UploadHandler uploader = new UploadHandlerRaw(body); uploader.contentType = contentType; wr.uploadHandler = uploader; wr.SetRequestHeader("Content-Type", "application/octet-stream"); yield return(wr.SendWebRequest()); if (wr.isNetworkError || wr.isHttpError) { Debug.Log("error uploading: " + wr.error); } Debug.Log("upload complete"); }
public UnityWebRequest CreateRequest(byte[] photo) { DownloadHandler download = new DownloadHandlerBuffer(); List <IMultipartFormSection> multipartFormSections = new List <IMultipartFormSection>(); multipartFormSections.Add(new MultipartFormFileSection("img", photo, "test.jpg", "image/jpeg")); byte[] boundary = UnityWebRequest.GenerateBoundary(); UploadHandler upload = new UploadHandlerRaw(UnityWebRequest.SerializeFormSections(multipartFormSections, boundary)); string url = "http://" + serverAddress + serverPath; UnityWebRequest www = new UnityWebRequest(url, "POST", download, upload); www.SetRequestHeader("Content-Type", "multipart/form-data; boundary=" + Encoding.UTF8.GetString(boundary)); return(www); }
public static RequestBody From(FormData form) { // https://answers.unity.com/questions/1354080/unitywebrequestpost-and-multipartform-data-not-for.html List <IMultipartFormSection> formData = form.MultipartForm(); // generate a boundary then convert the form to byte[] byte[] boundary = UnityWebRequest.GenerateBoundary(); byte[] formSections = UnityWebRequest.SerializeFormSections(formData, boundary); // my termination string consisting of CRLF--{boundary}-- byte[] terminate = Encoding.UTF8.GetBytes(String.Concat("\r\n--", Encoding.UTF8.GetString(boundary), "--")); // Make complete body from the two byte arrays byte[] bodyRaw = new byte[formSections.Length + terminate.Length]; Buffer.BlockCopy(formSections, 0, bodyRaw, 0, formSections.Length); Buffer.BlockCopy(terminate, 0, bodyRaw, formSections.Length, terminate.Length); // Set the content type string contentType = String.Concat("multipart/form-data; boundary=", Encoding.UTF8.GetString(boundary)); return(new RequestBody(contentType, bodyRaw)); }
protected UnityWebRequest CreateMultipartUpload(UnityWebRequest webRequest) { var boundary = UnityWebRequest.GenerateBoundary(); var metadata = new MultipartFormDataSection(null, JsonUtils.ToJsonPrivateCamel(RequestData), REQUEST_CONTENT_TYPE); var content = new MultipartFormDataSection(null, RequestPayload, PayloadMimeType); var formData = UnityWebRequest.SerializeFormSections(new List <IMultipartFormSection> { metadata, content }, boundary); // End boundary is missing; adding it manually. var endBoundary = Encoding.ASCII.GetBytes(string.Format("\r\n--{0}--", Encoding.ASCII.GetString(boundary))); var data = new byte[formData.Length + endBoundary.Length]; Buffer.BlockCopy(formData, 0, data, 0, formData.Length); Buffer.BlockCopy(endBoundary, 0, data, formData.Length, endBoundary.Length); webRequest.uploadHandler = new UploadHandlerRaw(data); webRequest.SetRequestHeader("Content-Type", string.Concat("multipart/related; boundary=", Encoding.ASCII.GetString(boundary))); return(webRequest); }
public virtual void PreSend(ref UnityWebRequest www) { if (multiparts.Count == 0) { return; } var boundary = UnityWebRequest.GenerateBoundary(); var formSections = UnityWebRequest.SerializeFormSections(multiparts, boundary); var terminate = Encoding.UTF8.GetBytes(string.Concat("\r\n--", Encoding.UTF8.GetString(boundary), "--")); var body = new byte[formSections.Length + terminate.Length]; Buffer.BlockCopy(formSections, 0, body, 0, formSections.Length); Buffer.BlockCopy(terminate, 0, body, formSections.Length, terminate.Length); var contentType = string.Concat("multipart/form-data; boundary=", Encoding.UTF8.GetString(boundary)); var uploader = new UploadHandlerRaw(body) { contentType = contentType }; www.uploadHandler = uploader; www.downloadHandler = new DownloadHandlerBuffer(); }
private IEnumerator UploadWWW(string url, string requestType, List <IMultipartFormSection> body, System.Action <UnityWebRequest> callback) { WaitCursor.Show(); byte[] byteBoundary = UnityWebRequest.GenerateBoundary(); byte[] generated = UnityWebRequest.SerializeFormSections(body, byteBoundary); List <byte> generatedList = new List <byte>(); for (int i = 0; i < generated.Length; i++) { generatedList.Add(generated[i]); } // add end-boundary byte[] endBoundary = Encoding.ASCII.GetBytes("\r\n--" + Encoding.ASCII.GetString(byteBoundary) + "--"); for (int i = 0; i < endBoundary.Length; i++) { generatedList.Add(endBoundary[i]); } UnityWebRequest req = new UnityWebRequest(url); req.method = requestType; foreach (KeyValuePair <string, string> header in StandardHeader) { req.SetRequestHeader(header.Key, header.Value); } //string boundary = Encoding.ASCII.GetString(UnityWebRequest.GenerateBoundary()); //string strEndBoundary = "\r\n--" + boundary + "--"; //string formdataTemplate = "\r\n--" + boundary + // "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; //Dictionary<string, string> fields = new Dictionary<string, string>(); //fields.Add("actionid", "testaction2"); //fields.Add("actionname", "testaction2"); //fields.Add("actiondesc", "a new action"); //string strBody = ""; //foreach (KeyValuePair<string, string> pair in fields) //{ // string formitem = string.Format(formdataTemplate, pair.Key, pair.Value); // strBody += formitem; //} //strBody += strEndBoundary; //Debug.Log(strBody); //byte[] bytes = Encoding.ASCII.GetBytes(strBody); req.uploadHandler = new UploadHandlerRaw(generatedList.ToArray()); // req.uploadHandler.contentType = "multipart/form-data; boundary=" + boundary; req.uploadHandler.contentType = "multipart/form-data; boundary=" + Encoding.ASCII.GetString(byteBoundary); req.downloadHandler = new DownloadHandlerBuffer(); yield return(req.Send()); WaitCursor.Hide(); if (callback != null) { callback(req); } }
/// <summary> /// Sending diagnostic report to Backtrace /// </summary> /// <param name="json">diagnostic data JSON</param> /// <param name="attachments">List of report attachments</param> /// <param name="queryAttributes">Query string attributes</param> /// <param name="callback">coroutine callback</param> /// <returns>Server response</returns> public IEnumerator Send(string json, List <string> attachments, Dictionary <string, string> queryAttributes, Action <BacktraceResult> callback) { var stopWatch = EnablePerformanceStatistics ? System.Diagnostics.Stopwatch.StartNew() : new System.Diagnostics.Stopwatch(); var requestUrl = queryAttributes != null ? GetParametrizedQuery(_serverUrl.ToString(), queryAttributes) : ServerUrl; List <IMultipartFormSection> formData = new List <IMultipartFormSection> { new MultipartFormFileSection("upload_file", Encoding.UTF8.GetBytes(json), "upload_file.json", "application/json") }; foreach (var file in attachments) { if (File.Exists(file) && new FileInfo(file).Length < 10000000) { formData.Add(new MultipartFormFileSection( string.Format("attachment__{0}", Path.GetFileName(file)), File.ReadAllBytes(file))); } } var boundaryIdBytes = UnityWebRequest.GenerateBoundary(); using (var request = UnityWebRequest.Post(requestUrl, formData, boundaryIdBytes)) { #if UNITY_2018_4_OR_NEWER if (_ignoreSslValidation) { request.certificateHandler = new BacktraceSelfSSLCertificateHandler(); } #endif request.SetRequestHeader("Content-Type", "multipart/form-data; boundary=" + Encoding.UTF8.GetString(boundaryIdBytes)); request.timeout = 15000; yield return(request.SendWebRequest()); BacktraceResult result; if (request.responseCode == 429) { result = new BacktraceResult() { Message = "Server report limit reached", Status = Types.BacktraceResultStatus.LimitReached }; if (OnServerResponse != null) { OnServerResponse.Invoke(result); } } else if (request.responseCode == 200 && (!request.isNetworkError || !request.isHttpError)) { result = BacktraceResult.FromJson(request.downloadHandler.text); _shouldDisplayFailureMessage = true; if (OnServerResponse != null) { OnServerResponse.Invoke(result); } } else { PrintLog(request); var exception = new Exception(request.error); result = BacktraceResult.OnNetworkError(exception); if (OnServerError != null) { OnServerError.Invoke(exception); } } if (callback != null) { callback.Invoke(result); } if (EnablePerformanceStatistics) { stopWatch.Stop(); Debug.Log(string.Format("Backtrace - JSON send time: {0}μs", stopWatch.GetMicroseconds())); } yield return(result); } }
UnityWebRequest CreateWebRequest(string url, LootLockerServerRequest request) { UnityWebRequest webRequest; switch (request.httpMethod) { case LootLockerHTTPMethod.UPLOAD: webRequest = UnityWebRequest.Post(url, request.form); break; case LootLockerHTTPMethod.POST: case LootLockerHTTPMethod.PATCH: // Defaults are fine for PUT case LootLockerHTTPMethod.PUT: if (request.payload == null && request.upload != null) { List <IMultipartFormSection> form = new List <IMultipartFormSection> { new MultipartFormFileSection(request.uploadName, request.upload, System.DateTime.Now.ToString(), request.uploadType) }; // generate a boundary then convert the form to byte[] byte[] boundary = UnityWebRequest.GenerateBoundary(); byte[] formSections = UnityWebRequest.SerializeFormSections(form, boundary); // Set the content type - NO QUOTES around the boundary string contentType = String.Concat("multipart/form-data; boundary=--", Encoding.UTF8.GetString(boundary)); //Debug.LogError("Content type Set: " + contentType); // Make my request object and add the raw body. Set anything else you need here webRequest = new UnityWebRequest(); webRequest.SetRequestHeader("Content-Type", "multipart/form-data; boundary=--"); webRequest.uri = new Uri(url); Debug.Log(url); //the url is wrong in some cases webRequest.uploadHandler = new UploadHandlerRaw(formSections); webRequest.uploadHandler.contentType = contentType; webRequest.useHttpContinue = false; // webRequest.method = "POST"; webRequest.method = UnityWebRequest.kHttpVerbPOST; } else { string json = (request.payload != null && request.payload.Count > 0) ? JsonConvert.SerializeObject(request.payload) : request.jsonPayload; #if UNITY_EDITOR LootLockerSDKManager.DebugMessage("REQUEST BODY = " + json); #endif byte[] bytes = System.Text.Encoding.UTF8.GetBytes(string.IsNullOrEmpty(json) ? "{}" : json); webRequest = UnityWebRequest.Put(url, bytes); webRequest.method = request.httpMethod.ToString(); } break; case LootLockerHTTPMethod.OPTIONS: case LootLockerHTTPMethod.HEAD: case LootLockerHTTPMethod.GET: // Defaults are fine for GET webRequest = UnityWebRequest.Get(url); webRequest.method = request.httpMethod.ToString(); break; case LootLockerHTTPMethod.DELETE: // Defaults are fine for DELETE webRequest = UnityWebRequest.Delete(url); break; default: throw new System.Exception("Invalid HTTP Method"); } if (baseHeaders != null) { foreach (KeyValuePair <string, string> pair in baseHeaders) { if (pair.Key == "Content-Type" && request.upload != null) { continue; } webRequest.SetRequestHeader(pair.Key, pair.Value); } } if (request.extraHeaders != null) { foreach (KeyValuePair <string, string> pair in request.extraHeaders) { webRequest.SetRequestHeader(pair.Key, pair.Value); } } return(webRequest); }
IEnumerator UploadJPGwithGPS(byte[] bytes, string apiURL, float langitude, float latitude, float hdop, Action <string, bool> getJsonCameraObjects) { localizationStatus = LocalizationStatus.WaitForAPIAnswer; Debug.Log("bytes = " + bytes.Length); List <IMultipartFormSection> form = new List <IMultipartFormSection>(); string rotationDevice = "90"; if (!editorTestMode) { if (Input.deviceOrientation == DeviceOrientation.Portrait) { rotationDevice = "0"; } if (Input.deviceOrientation == DeviceOrientation.LandscapeRight) { rotationDevice = "90"; } if (Input.deviceOrientation == DeviceOrientation.PortraitUpsideDown) { rotationDevice = "180"; } if (Input.deviceOrientation == DeviceOrientation.LandscapeLeft) { rotationDevice = "270"; } } string jsona = "{\"gps\":{\"latitude\":" + langitude + ",\"longitude\":" + latitude + ",\"hdop\":" + hdop + "},\"rotation\": " + rotationDevice + ",\"mirrored\": false}"; uim.gpsDebug(langitude, latitude, hdop); Debug.Log("" + jsona); form.Add(new MultipartFormFileSection("image", bytes, "test.jpg", "image/jpeg")); form.Add(new MultipartFormDataSection("description", jsona)); byte[] boundary = UnityWebRequest.GenerateBoundary(); Debug.Log(apiURL + "/api/localizer/localize"); var w = UnityWebRequest.Post(apiURL + "/api/localizer/localize", form, boundary); w.SetRequestHeader("Accept-Encoding", "gzip, deflate, br"); w.SetRequestHeader("Accept", "application/vnd.myplace.v2+json"); w.SetRequestHeader("user-agent", "Unity AC-viewer based app, name: " + Application.productName + ", Device: " + SystemInfo.deviceModel); Debug.Log("Uploading Screenshot started..."); yield return(w.SendWebRequest()); if (w.isNetworkError || w.isHttpError) { Debug.Log(w.error); localizationStatus = LocalizationStatus.ServerError; } else { Debug.Log("Finished Uploading Screenshot"); } Debug.Log(w.downloadHandler.text); var jsonParse = JSON.Parse(w.downloadHandler.text); string sid = null; if (jsonParse["camera"] != null) { sid = jsonParse["reconstruction_id"]; } tempScale3d = 1; getJsonCameraObjects(w.downloadHandler.text, false); }
static bool PutRequestInit <O, I, W>(string endpoint, out UnityWebRequest uwr, out IWorker <O, I> worker, I param, IWorker <O, I> workerDefault = null, string token = null, params IMultipartFormSection[] parts) where W : IWorker <O, I>, new() where O : class where I : class { bool useMock = false; url = Instance.urlParam; TokenPrefix = Instance.tokenPrefix; string requestUrl = $"{url}/{endpoint}"; if (endpoint.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { requestUrl = endpoint; } string json = null; byte[] jsonToSend = new byte[1]; if (workerDefault == null) { worker = new W(); } else { worker = workerDefault; } uwr = new UnityWebRequest($"{requestUrl}", "PUT"); if (MocksResource != MocksResource.NONE) { var key = typeof(W).ToString(); if (!mocks.ContainsKey(key)) { key = $"PUT:{endpoint}"; } if (mocks.ContainsKey(key)) { ToolsDebug.Log($"Use mock for Key:{key} Value:{mocks[key]?.Substring(0, Mathf.Min(mocks[key].Length, Instance.logLimit))}"); useMock = true; } else { ToolsDebug.Log($"Mocks for key {endpoint} or {typeof(W).ToString()} not found. Try real request."); } } if (typeof(I) == typeof(Texture2D)) { Texture2D sendTexture = param as Texture2D; json = "Texture2D"; jsonToSend = ImageConversion.EncodeToPNG(sendTexture); uwr.uploadHandler = (UploadHandler) new UploadHandlerRaw(jsonToSend); uwr.SetRequestHeader("Content-Type", "image/png"); } else { if (param != null) { json = worker.Serialize(param); jsonToSend = new System.Text.UTF8Encoding().GetBytes(json); } if (parts != null && parts.Length != 0) { //TODO: //Finish it Debug.Log("WTF"); List <IMultipartFormSection> formData = new List <IMultipartFormSection>(); formData.Add(new MultipartFormDataSection("JSON Body", json, "application/json")); formData.AddRange(parts); var boundary = UnityWebRequest.GenerateBoundary(); byte[] formSections = UnityWebRequest.SerializeFormSections(formData, boundary); uwr = UnityWebRequest.Put($"{requestUrl}", formSections); uwr.SetRequestHeader("Content-Type", "multipart/form-data; boundary=" + System.Text.Encoding.UTF8.GetString(boundary)); uwr.uploadHandler.contentType = "multipart/form-data; boundary=" + System.Text.Encoding.UTF8.GetString(boundary); } else { uwr.uploadHandler = (UploadHandler) new UploadHandlerRaw(jsonToSend); uwr.uploadHandler.contentType = "application/json"; } } uwr.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); if (!string.IsNullOrEmpty(token)) { uwr.SetRequestHeader("Authorization", $"{TokenPrefix} {token}"); } ToolsDebug.Log($"{UnityWebRequest.kHttpVerbPUT}: {requestUrl} {uwr.GetRequestHeader("Authorization")} JSONBody:{json?.Substring(0, Mathf.Min(json.Length, Instance.logLimit))}"); worker.Request = param; worker.Start(); return(useMock); }
public IEnumerator UploadFile() { List <IMultipartFormSection> formData = new List <IMultipartFormSection>(); // MultipartFormDataSection not accepting empty values, create a placeholder value and replace later string xAmzSecurityTokenFillerKey = "xAmzSecurityToken.pnFormField.Key"; // Encrypted file is garbled string xAmzSecurityTokenFillerFile = "xFile.pnFormField.Value"; foreach (PNFormField pnFormField in SendFileToS3FileUploadRequestData.FormFields) { if (string.IsNullOrEmpty(pnFormField.Value)) { formData.Add(new MultipartFormDataSection(pnFormField.Key, xAmzSecurityTokenFillerKey)); } else { formData.Add(new MultipartFormDataSection(pnFormField.Key, pnFormField.Value)); } if (pnFormField.Key.Equals("Content-Type")) { SendFileToS3ContentType = pnFormField.Value; } } #if (ENABLE_PUBNUB_LOGGING) this.PubNubInstance.PNLog.WriteToLog(string.Format("SendFileToS3FileUploadRequestData.URL: {0}", SendFileToS3FileUploadRequestData.URL), PNLoggingMethod.LevelInfo); #endif byte[] boundary = UnityWebRequest.GenerateBoundary(); string contentType = String.Concat("multipart/form-data; boundary=", Encoding.UTF8.GetString(boundary)); byte[] formSections = UnityWebRequest.SerializeFormSections(formData, boundary); string formSectionString = Encoding.UTF8.GetString(formSections); formSectionString = formSectionString.Replace(xAmzSecurityTokenFillerKey, ""); formSectionString = formSectionString.Replace(string.Format("--{0}--", Encoding.UTF8.GetString(boundary)), string.Format("--{0}", Encoding.UTF8.GetString(boundary))); formSections = Encoding.ASCII.GetBytes(formSectionString); // Do not use SerializeFormSections on the payload. string formSectionFileHeader = string.Format("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\nContent-Type: {1}\r\n\r\n", SendFileToS3FileName, SendFileToS3ContentType); byte[] formSectionFileHeaderBytes = Encoding.ASCII.GetBytes(formSectionFileHeader); byte[] formSectionFileValue = System.IO.File.ReadAllBytes(SendFileToS3FilePath); byte[] terminationString = Encoding.UTF8.GetBytes(String.Concat("\r\n--", Encoding.UTF8.GetString(boundary), "--")); byte[] boundaryWithHyphensAndNL = Encoding.UTF8.GetBytes(String.Format("\r\n--{0}--\r\n", Encoding.UTF8.GetString(boundary))); byte[] body = new byte[formSections.Length + formSectionFileHeaderBytes.Length + formSectionFileValue.Length + boundaryWithHyphensAndNL.Length + terminationString.Length]; Buffer.BlockCopy(formSections, 0, body, 0, formSections.Length); Buffer.BlockCopy(formSectionFileHeaderBytes, 0, body, formSections.Length, formSectionFileHeaderBytes.Length); Buffer.BlockCopy(formSectionFileValue, 0, body, formSections.Length + formSectionFileHeaderBytes.Length, formSectionFileValue.Length); Buffer.BlockCopy(boundaryWithHyphensAndNL, 0, body, formSections.Length + formSectionFileHeaderBytes.Length + formSectionFileValue.Length, boundaryWithHyphensAndNL.Length); Buffer.BlockCopy(terminationString, 0, body, formSections.Length + formSectionFileHeaderBytes.Length + formSectionFileValue.Length + boundaryWithHyphensAndNL.Length, terminationString.Length); uploadWWW = new UnityWebRequest(SendFileToS3FileUploadRequestData.URL); UploadHandler uploader = new UploadHandlerRaw(body); uploadWWW.downloadHandler = new DownloadHandlerBuffer(); uploader.contentType = contentType; uploadWWW.uploadHandler = uploader; uploadWWW.method = "POST"; yield return(uploadWWW.SendWebRequest()); UploadCallback(new PNSendFileToS3Result { IsHttpError = uploadWWW.isHttpError, IsNetworkError = uploadWWW.isNetworkError, Text = uploadWWW.downloadHandler.text }, CreatePNStatus(uploadWWW)); }
/// <summary> /// Send minidump to Backtrace /// </summary> /// <param name="minidumpPath">Path to minidump</param> /// <param name="attachments">List of attachments</param> /// <param name="callback">Callback</param> /// <returns>Server response</returns> public IEnumerator SendMinidump(string minidumpPath, IEnumerable <string> attachments, Action <BacktraceResult> callback = null) { if (attachments == null) { attachments = new List <string>(); } var stopWatch = EnablePerformanceStatistics ? System.Diagnostics.Stopwatch.StartNew() : new System.Diagnostics.Stopwatch(); var minidumpBytes = File.ReadAllBytes(minidumpPath); if (minidumpBytes == null || minidumpBytes.Length == 0) { yield break; } List <IMultipartFormSection> formData = new List <IMultipartFormSection> { new MultipartFormFileSection("upload_file", minidumpBytes) }; foreach (var file in attachments) { if (File.Exists(file) && new FileInfo(file).Length < 10000000) { formData.Add(new MultipartFormFileSection( string.Format("attachment__{0}", Path.GetFileName(file)), File.ReadAllBytes(file))); } } yield return(new WaitForEndOfFrame()); var boundaryIdBytes = UnityWebRequest.GenerateBoundary(); using (var request = UnityWebRequest.Post(_minidumpUrl, formData, boundaryIdBytes)) { #if UNITY_2018_4_OR_NEWER if (_ignoreSslValidation) { request.certificateHandler = new BacktraceSelfSSLCertificateHandler(); } #endif request.SetRequestHeader("Content-Type", string.Format("multipart/form-data; boundary={0}", Encoding.UTF8.GetString(boundaryIdBytes))); request.timeout = 15000; yield return(request.SendWebRequest()); var result = request.isNetworkError || request.isHttpError ? new BacktraceResult() { Message = request.error, Status = Types.BacktraceResultStatus.ServerError } : BacktraceResult.FromJson(request.downloadHandler.text); if (callback != null) { callback.Invoke(result); } if (EnablePerformanceStatistics) { stopWatch.Stop(); Debug.Log(string.Format("Backtrace - minidump send time: {0}μs", stopWatch.GetMicroseconds())); } yield return(result); } }
/// <summary> /// Send the web request to the server /// </summary> /// <returns>An UnityWebRequestAsyncOperation object.</returns> /// <param name="request">An UnityWebRequest object.</param> /// <param name="options">An options object.</param> public static IEnumerator SendWebRequest(UnityWebRequest request, RequestHelper options) { byte[] bodyRaw = options.BodyRaw; string contentType = "application/json"; if (options.Body != null || !string.IsNullOrEmpty(options.BodyString)) { var bodyString = options.BodyString; if (options.Body != null) { bodyString = JsonUtility.ToJson(options.Body); } bodyRaw = Encoding.UTF8.GetBytes(bodyString.ToCharArray()); } else if (options.SimpleForm != null && options.SimpleForm.Count > 0) { bodyRaw = UnityWebRequest.SerializeSimpleForm(options.SimpleForm); contentType = "application/x-www-form-urlencoded"; } else if (options.FormSections != null && options.FormSections.Count > 0) { byte[] boundary = UnityWebRequest.GenerateBoundary(); byte[] formSections = UnityWebRequest.SerializeFormSections(options.FormSections, boundary); byte[] terminate = Encoding.UTF8.GetBytes(string.Concat("\r\n--", Encoding.UTF8.GetString(boundary), "--")); bodyRaw = new byte[formSections.Length + terminate.Length]; System.Buffer.BlockCopy(formSections, 0, bodyRaw, 0, formSections.Length); System.Buffer.BlockCopy(terminate, 0, bodyRaw, formSections.Length, terminate.Length); contentType = string.Concat("multipart/form-data; boundary=", Encoding.UTF8.GetString(boundary)); } else if (options.FormData is WWWForm) { //The Content-Type header will be copied from the formData parameter contentType = string.Empty; } if (!string.IsNullOrEmpty(options.ContentType)) { contentType = options.ContentType; } #if UNITY_2018_1_OR_NEWER if (options.CertificateHandler is CertificateHandler) { request.certificateHandler = options.CertificateHandler; } #endif if (options.UploadHandler is UploadHandler) { request.uploadHandler = options.UploadHandler; } if (bodyRaw != null) { request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw); request.uploadHandler.contentType = contentType; } if (options.DownloadHandler is DownloadHandler) { request.downloadHandler = options.DownloadHandler; } else { request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); } if (!string.IsNullOrEmpty(contentType)) { request.SetRequestHeader("Content-Type", contentType); } foreach (var header in RestClient.DefaultRequestHeaders) { request.SetRequestHeader(header.Key, header.Value); } foreach (var header in options.Headers) { request.SetRequestHeader(header.Key, header.Value); } if (options.Timeout.HasValue) { request.timeout = options.Timeout.Value; } if (options.ChunkedTransfer.HasValue) { request.chunkedTransfer = options.ChunkedTransfer.Value; } if (options.UseHttpContinue.HasValue) { request.useHttpContinue = options.UseHttpContinue.Value; } if (options.RedirectLimit.HasValue) { request.redirectLimit = options.RedirectLimit.Value; } options.Request = request; #if UNITY_2017_2_OR_NEWER yield return(request.SendWebRequest()); #else yield return(request.Send()); #endif }
IEnumerator OnCollisionEnter(Collision collision) { if (!hitOk) { yield break; } ContactPoint contact = collision.contacts[0]; culprit = contact.otherCollider; current = contact.thisCollider; print("Collision"); if (current.name == "reset") { resetBlocks(); yield break; } if (culprit.name == "Beamer") { print("Collision With " + current.name + " (Tag: " + current.tag + ") From " + culprit.name); imageName = current.name + ".png"; image = Path.Combine(Application.streamingAssetsPath, imageName); List <IMultipartFormSection> form = new List <IMultipartFormSection> { new MultipartFormFileSection("file", File.ReadAllBytes(image), imageName, "image/jpeg") }; byte[] boundary = UnityWebRequest.GenerateBoundary(); byte[] formSections = UnityWebRequest.SerializeFormSections(form, boundary); byte[] terminate = Encoding.UTF8.GetBytes(String.Concat("\r\n--", Encoding.UTF8.GetString(boundary), "--")); byte[] body = new byte[formSections.Length + terminate.Length]; Buffer.BlockCopy(formSections, 0, body, 0, formSections.Length); Buffer.BlockCopy(terminate, 0, body, formSections.Length, terminate.Length); string contentType = String.Concat("multipart/form-data; boundary=", Encoding.UTF8.GetString(boundary)); UnityWebRequest wr = new UnityWebRequest(serverPath, "POST"); UploadHandler uploader = new UploadHandlerRaw(body); uploader.contentType = contentType; wr.uploadHandler = uploader; wr.downloadHandler = new DownloadHandlerBuffer(); yield return(wr.SendWebRequest()); if (wr.isNetworkError || wr.isHttpError) { print(wr.error); hitClock = 0; } else { string json = wr.downloadHandler.text; JSONNode jsonData = JSON.Parse(System.Text.Encoding.UTF8.GetString(wr.downloadHandler.data)); if (jsonData["Diagnosis"] == "Negative") { print("Negative Classification"); if (imageName.Contains("Non-Covid")) { current.GetComponent <MeshRenderer>().material.color = Color.green; } else { current.GetComponent <MeshRenderer>().material.color = Color.cyan; } } else if (jsonData["Diagnosis"] == "Positive") { print("Postive Classification"); if (imageName.Contains("Non-Covid")) { current.GetComponent <MeshRenderer>().material.color = Color.magenta; } else { current.GetComponent <MeshRenderer>().material.color = Color.red; } } hitClock = 0; } } }
IEnumerator UploadVideo(string ticketBarcode) { var dataAPI = "[{" + "\"name\": \"\"," + "\"description\": \"\"," + "\"title\": \"\"," + "\"tags\": [\"morphVideo\"]," + "\"captureType\": 10810," + "\"mediaType\": \"Video\"," + "\"deviceToken\": \"\"," + "\"type\": 10102," + "\"visibility\": 10301," + "\"ticketBarcodes\": [\"" + ticketBarcode + "\"]," + "\"guestId\": \"\"," + "\"data\": {}" + "}]"; // create data for request List <IMultipartFormSection> formData = new List <IMultipartFormSection>(); formData.Add(new MultipartFormDataSection("info", dataAPI)); // video file to bytes byte[] videoBytes = File.ReadAllBytes(Application.dataPath + "/video.mp4"); formData.Add(new MultipartFormFileSection("files", videoBytes, "video.mp4", "video/mp4")); // headers for post api Hashtable postHeader = new Hashtable(); byte[] boundary = UnityWebRequest.GenerateBoundary(); byte[] formSections = UnityWebRequest.SerializeFormSections(formData, boundary); // create request UnityWebRequest www = UnityWebRequest.Post(uploadUrl, formData); byte[] terminate = Encoding.UTF8.GetBytes(String.Concat("\r\n--", Encoding.UTF8.GetString(boundary), "--")); byte[] body = new byte[formSections.Length + terminate.Length]; // buffer for check length Buffer.BlockCopy(formSections, 0, body, 0, formSections.Length); Buffer.BlockCopy(terminate, 0, body, formSections.Length, terminate.Length); // multipart header UploadHandler uploader = new UploadHandlerRaw(body); // new UploadHandlerRaw(formSections); uploader.contentType = String.Concat("multipart/form-data; boundary=", Encoding.UTF8.GetString(boundary)); www.uploadHandler = uploader; // send request yield return(www.Send()); if (www.isNetworkError || www.isHttpError) { Debug.Log("Download source Error: // " + www.error + "/// Details: " + www.downloadHandler.text + "///" + www.responseCode); } else { Debug.Log("Form upload complete!" + www.downloadHandler.text); } }