Unity3D - Post is empty when doing a UnityWebRequest

随声附和 提交于 2021-01-29 08:37:26

问题


I'm doing a UnityWebrequest and it's working fine, but upon checking what's is the post in my PHP I found that the post is an empty array and the file is aswell. I found a StackOverflow post that has a similar problem. But it's solution did not work for me. So why is the post and file empty? I'm running this on a local server.

UnityWebRequest POST to PHP not work

Web request

static IEnumerator Post(string url, string bodyJsonString)
{
    UnityWebRequest request = new UnityWebRequest(url, "POST");
    request.chunkedTransfer = false;
    Debug.Log(bodyJsonString);
    byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
    request.uploadHandler = new UploadHandlerRaw(bodyRaw);
    Debug.Log(request.uploadHandler.data.Length);
    request.downloadHandler = new DownloadHandlerBuffer();
    request.SetRequestHeader("Content-Type", "application/json");
    yield return request.SendWebRequest();
    Debug.Log("Status Code: " + request.responseCode);
    Debug.Log(request.downloadHandler.text);
}

Php

<?php
echo "POST: ";
print_r($_POST);
var_dump($_POST);

echo "Files: ";
print_r($_FILES);
var_dump($_FILES);

Debugs

{"testJson":1}

8

Status Code: 200

POST: Array ( ) array(0) { } Files: Array ( ) array(0) { }


回答1:


I had the same problem and this worked for me.

after

UnityWebRequest request = new UnityWebRequest(url, "POST");

add

request.chunkedTransfer = false;

The thing that had me stumped for ages was I needed to have the filename in the url. I was using index.php so I was just using the directory path for the url. Soon as I used the path including the filename it started working fine.




回答2:


The problem was solved when I added content via a WWWForm. Then the $_Post array was populated.

https://docs.unity3d.com/ScriptReference/WWWForm.html



来源:https://stackoverflow.com/questions/58486388/unity3d-post-is-empty-when-doing-a-unitywebrequest

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!