简体   繁体   English

如何获取 HTTP Post 请求的 JSON 内容?

[英]How to get the JSON content of a HTTP Post request?

I want to send a JSON file from my Unity application to my Laravel backend.我想将 JSON 文件从我的 Unity 应用程序发送到我的 Laravel 后端。 It seems there is something wrong with my post request but I can't figure out what it is.我的帖子请求似乎有问题,但我无法弄清楚它是什么。

Sending the request using Unity使用 Unity 发送请求

public void SendRequest()
        {
            // serializable struct
            OfferData data = new OfferData(OfferSize.JUMBO, OfferType.AD, 50, 10);

            StartCoroutine(RequestHandler.Post(API_URL + "shop/store", JsonUtility.ToJson(data), (response) =>
            {
                if (response == null)
                {
                    return;
                }
                // success
                Debug.Log(response);
            }));
        }

The JSON: JSON:

{
"size":3,
"type":1,
"gold":50,
"gems":10
}

The post function in the RequestHandler: RequestHandler 中的 post 函数:

public static IEnumerator Post(string uri, string data, Action<string> response)
        {
            UnityWebRequest webRequest = UnityWebRequest.Post(uri, data);
            webRequest.SetRequestHeader("Content-Type", "application/json");

            yield return webRequest.SendWebRequest();

            if (webRequest.isNetworkError)
            {
                Error(webRequest.error);
                response(null);
            }
            else
            {
                response(webRequest.downloadHandler.text);
            }
        }

If I'm sending the UnityWebRequest with Laravel will send a success response, however, the printed array (see below) is just empty.如果我发送UnityWebRequest与Laravel会发送一个成功响应,但是,印刷阵列(见下文)就是一句。 Laravel can not encode the JSON. Laravel 无法对 JSON 进行编码。

Receiving the request in Laravel在 Laravel 中接收请求

This is where the HTTP Post request is being accessed in my controller function:这是在我的控制器函数中访问 HTTP Post 请求的地方:

public function store(Request $request)
{
    Log::debug($request->json()->all());
}

Which produces the expected result when using Postman:使用 Postman 时会产生预期的结果:

array ('size' => 3, 'type' => 1, 'gold' => 50, 'gems' => 10)

Sending a similar request with the same JSON using Unity:使用 Unity 发送具有相同 JSON 的类似请求:

array ()

When I use $request->getContent() I can actually see my data.当我使用$request->getContent()我实际上可以看到我的数据。 Why is the array empty?为什么数组是空的?

Successful request header请求头成功

The request header when sent from Postman:从 Postman 发送时的请求标头:

{
"content-type": "application/json",
"user-agent": "PostmanRuntime/7.21.0",
"accept": "*/*",
"cache-control": "no-cache",
"postman-token": "d8f323fc-f2c8-49b8-a023-2955122fa20e",
"host": "127.0.0.1:8000",
"accept-encoding": "gzip, deflate",
"content-length": "119",
"cookie": "XSRF-TOKEN=eyJpdiI6IkRyU1RqSkppcVdyUmpuVHI2Ym55XC9RPT0iLCJ2YWx1ZSI6ImQrc1QrOTcyWE1GSXM3SGQrVlBsTG1lZ0dXd1FCQlRPellTQm83Z0FkWFc0UktjUW9PNHRqS3B3Z2Rya1ZZS2IiLCJtYWMiOiIxMmNlZTFiODc2MTlmNmVhYjI3ZGI1MTQ1NTM2MGFjODQ4YjZhNzdlMmM4NWQwM2NiYzk1MjkzYzNiYjBmNTA5In0%3D; recludo_session=eyJpdiI6ImFLcUdCdU1WU2JzazNEaEFyaGoxbnc9PSIsInZhbHVlIjoiT1VtNzl4XC9HMW5reTdKUGNDdlBXMVdLK3hMNFR3Q2JxMzA1RVY3NWdVdmV5akJhbnBKeU9YdU5JSmdPdGYyNWUiLCJtYWMiOiI4MWJjOGVhMTcxNDI3M2VjNTU0MDc3NmNkZDU0NjZlMzhmYWI1MjRlZGNlZjhhNGEyNmNjMmY3YThiMzAyODNhIn0%3D",
"connection": "keep-alive"
}

Faulty request header错误的请求头

The request header when sent from Unity:从 Unity 发送时的请求标头:

{
"host": "127.0.0.1:8000",
"user-agent": "UnityPlayer/2019.2.8f1 (UnityWebRequest/1.0, libcurl/7.52.0-DEV)",
"accept": "*/*",
"accept-encoding": "deflate, gzip",
"cookie": "XSRF-TOKEN=eyJpdiI6IlJhZE52emU1Z3hYUnVOWmtMbEdZa0E9PSIsInZhbHVlIjoibkdabkhZVnM1ZUYwSklvMzYrSHVLQ0Q5Y2NvRlVTMEhJOHpqMGFCSEZLZVQwd2NnT3NrUmNrXC9cL2Z4XC92M0J0QSIsIm1hYyI6Ijg4ZDUwZDQ4MWQ3OWM3ZjNlOTcxOWE3NzMxYjI1MmQ3NGQ2YzgwMWQ2MDE2YTQ5NTI3NWQ3MTg2ODM4NjMxY2UifQ%3D%3D; recludo_session=eyJpdiI6InoyMktDN3ByR1hYR0tHWCtvdmhOckE9PSIsInZhbHVlIjoiamZJVnlDbVYwZkdBU1wvMXhMeG1sWU5LdDY0d0NnQ0VucE1OK05UNDhUOG1Ya2o5ZUJIcFdaSktuakcrQjJqN1QiLCJtYWMiOiI1YTc5YTE5NDNhNjY5NWRlYzlmMDlkOGIyMWRiYTAzYzMwZTkwNzAzYjBhNTA2OGViOTUyOTlkYzMzYWJlMjA3In0%3D",
"content-type": "application/json",
"x-unity-version": "2019.2.8f1",
"content-length": "215"
}

What am I missing?我错过了什么? Please let me know if you need any more information.如果您需要更多信息,请告诉我。

The UnityWebRequest.Post send urlencoded data like UnityWebRequest.Post发送urlencoded数据,如

  1. uri The target URI to which form data will be transmitted. uri表单数据将传输到的目标 URI。
  2. postData Form body data. postData表单主体数据。 Will be URLEncoded prior to transmission.将在传输之前进行URLEncoded

you should need to decode the content using urldecode method in php.您应该需要在 php 中使用urldecode方法解码内容。 Like喜欢

$decoded = urldecode($request);

to parse json to object:将 json 解析为对象:

$data = json_decode($decoded);

to get attribute of json.获取json的属性。

$data->{attribute};

I'm still not sure why it doesn't work out of the box but I figured out how to fix this issue.我仍然不确定为什么它不能开箱即用,但我想出了如何解决这个问题。

Add a raw upload handler to the UnityWebRequest :UnityWebRequest添加一个原始上传处理程序:

UnityWebRequest webRequest = UnityWebRequest.Post(uri, data);

// Fix: Add upload handler and pass json as bytes array
webRequest.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(data));

webRequest.SetRequestHeader("Content-Type", "application/json");
yield return webRequest.SendWebRequest();

The JSON data can now be resolved correctly by Laravel. Laravel 现在可以正确解析 JSON 数据。

Sebastian Feistl's answer was the way to go for me, but instead of setting the "Content-Type" for the whole request as "application/json", it would only work if I set it for the uploadHandler: Sebastian Feistl 的回答是适合我的方法,但不是将整个请求的“Content-Type”设置为“application/json”,它只有在我为 uploadHandler 设置时才有效:

webRequest.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(data));
webRequest.uploadHandler.contentType = "application/json";

Experimenting with Postman, I found out that the "Content-Length" header is also necessary for this request (at least in my case) and I think that the uploadHandler helps in that regard too, as it sets the content in bytes, therefore the length as well.尝试 Postman,我发现“Content-Length”标头对于这个请求也是必要的(至少在我的情况下),我认为 uploadHandler 在这方面也有帮助,因为它以字节为单位设置内容,因此长度也是如此。 This is only speculation, though.不过,这只是猜测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM