dousigan0499
2017-03-12 21:07
浏览 104

带有json响应的PHP Http Post请求:没有有效的json

If I send the following request to an API, it says, that I use no valid JSON string. How can I transform my JSON in a valid PHP post request? I'm using guzzle:

$client = new Client();
$res = $client->request('POST', 'https://fghfgh', [
    'auth' => ['user', 'pw']
]);
$res->getStatusCode();
$res->getHeader('application/json');


$res->getBody('{
     "category": "ETW",
     "date": "2017-03-02",
     "address": {
         "nation": "DE",
         "street": "abc",
         "house_number": "7",
         "zip": "80637",
         "town": "München"
     },
     "construction_year": "1932",
     "living_area": "117.90",
     "elevator": false,
     "garages": false
}');
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dscrn1974 2017-03-12 21:17
    已采纳

    as mentioned in the documentation

    you need to pass the required headers to your response object as follows:

    $res = $client->request('POST', 'https://fghfgh', [
        'auth' => ['user', 'pw'],
        'headers' => [
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
        ]
    ]);
    
    已采纳该答案
    打赏 评论
  • dongmi1663 2017-03-12 21:21

    When I let php decode the json it won't give any errors, so the first thing that comes into mind is the München having an umlaut. What happens if you try this without using the umlaut?

    Having said that, I recommend you using an PHP array and encoding that into a json string instead of just typing the json string. This is because PHP can check the syntax for the array and you know whether it's right or wrong immediately. If option A doesn't work, this might fix your problem instead.

    It would look like this:

    $data = [
      'category' => 'ETW',
      'date' => '2017-03-02',
      'address' => [
        'nation' => 'DE',
        'street' => 'abc',
        'house_number' => 7,
        'zip' => '80637',
        'town' => 'Munchen'
      ],
      'construction_year' => 1932,
      'living_area' => '117.90',
      'elevator' => false,
      'garages' => false,
    ];
    
    $res->getBody(json_encode($data));
    
    打赏 评论
  • douba1067 2017-03-14 03:27

    Looks to me like you should be using the json option if your intention is to POST JSON data

    $client->post('https://fghfgh', [
        'auth' => ['user', 'pw'],
        'json' => [
            'category'          => 'ETW',
            'date'              => '2017-03-02',
            'address'           => [
                'nation'       => 'DE',
                'street'       => 'abc',
                'house_number' => '7',
                'zip'          => '80637',
                'town'         => 'München'
            ],
            'construction_year' => '1932',
            'living_area'       => '117.90',
            'elevator'          => false,
            'garages'           => false,
        ]
    ]);
    
    打赏 评论

相关推荐 更多相似问题