doutang6819 2017-11-25 15:34
浏览 255
已采纳

发送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?

  • 写回答

2条回答 默认 最新

  • dongyuan9892 2017-11-25 17:27
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条