2017-11-25 15:34

发送POST时$ _POST变量为空


I'm trying to send a JSON to my rest-api using RestSharp. Essentially I've created a model class for the json:

public class LogPostData
    public string LogMessage { get; set; }
    public string LogStackTrace { get; set; }
    public string LogUserId { get; set; }
    public string LogUserIp { get; set; }

so I perform the request in this way:

 var logPost = new LogPostData();
     logPost.LogMessage = "log message"
     logPost.LogStackTrace = "some content";

 var post = JsonConvert.SerializeObject(logPost);

 var client = new RestClient("url of rest api");

 var request = new RestRequest("methodApi", Method.PUT);
     request.RequestFormat = DataFormat.Json;
     request.AddParameter("application/json; charset=utf-8", post, ParameterType.RequestBody);
     request.RequestFormat = DataFormat.Json;

 var response = client.Execute(request);

as you can see I've created the object LogPostData and then serialized it using JsonConvert.SerializeObject.

I called the methodApi passing as parameter the json.

Now, inside my rest api, I did the following:

file_put_contents('debug.txt', serialize($_POST));

the content should be the variable that I sended with RestSharp on post variable, instead I get: a:0:{}

why my $_POST variable is empty?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dongyuan9892 dongyuan9892 4年前

    According to the PHP manual, $_POST works with application/x-www-form-urlencoded and multipart/form-data content types. You are sending JSON (application/json). Since $_POST is an associative array created from posted form data, and you are not posting a form, it's not surprising that it would be empty.

    To get the raw JSON from the request body you need to use php://input

    $json = file_get_contents('php://input');

    To deserialize the JSON to an object you can use json_decode.

    $logPostData = json_decode($json);

    If you want the data to be converted into an associative array like $_POST, you can pass true as the second parameter:

    $logPostData = json_decode($json, true);
    点赞 评论 复制链接分享
  • douzhenzu0247 douzhenzu0247 4年前

    Here's what you are sending (JSON):

    header: encoding-type=application/json
    body: {"param1":"I like horses", "param2":"they are cool"}

    This is what PHP needs in a POST request for the $_POST array to work (form submissions)

    header: encoding-type=application/x-www-form-urlencoded
    body: param1=I%20like%20horses&param2=they%20are%20cool

    If you are happy with sending json, you need to receive it properly. If you want to keep using PUT, then make a handler for it that expects JSON. (Based on this answer)

    $method = $_SERVER['REQUEST_METHOD'];
    if ('PUT' === $method) {
        $data = json_decode(file_get_contents('php://input'), true);
        var_dump($data); //$data contains put fields 
    点赞 评论 复制链接分享