Jump to content

[solved] WireHTTP POST sending application/json data problem


psy
 Share

Recommended Posts

I'm trying to post json data to an endpoint with:

<?php

        $http = new WireHttp();
        $http->setHeaders([
            'X-Auth-Token' => 'XXXXXX',
            'Accept'=> 'application/json',
            'content-type' => 'application/json'
        ]);
        $myEndPoint = "https://myendpoint.com/api";
        $params = [
            'parent_id' => 0,
            'name' => "My Name",
            'is_visible' => false
        ];
        $paramsJSON = json_encode($params);
        $http->setData($paramsJSON);

        $response = $http->post($myEndPoint);
        if($http->getError()) {
            echo "HTTP request failed: " . $http->getError();
            $this->die;
        }

        //.....
    }

It fails every time no matter how I present the $params with: HTTP request failed: 400 Bad Request:.

It works successfully when I post through Postman app.

The endpoint & headers are correct and used successfully elsewhere with $http->get

Help to fix much appreciated.

Edited by psy
Problem solved
Link to comment
Share on other sites

Hi @psy are you able to compare all the headers being sent by postman with all the headers you are going over from WireHTTP()? Perhaps something that's needed is missing.

Also, did you try changing "content-type" -> "Content-Type" ? Might be that the endpoint is being picky about case-sensitivity. Also, do you need to specify the character encoding?  Something like "Content-Type" => "application/json; charset=utf-8"?

Another thing to look at is the encoding flags for the json data. Might be that the way postman is encoding the payload is slightly different to the way PHP is encoding it. I'd dump the output of the json_encode() and carefully compare it to the format being sent from Postman (if it's possible to see it.)

Link to comment
Share on other sites

Thanks for the tips netcarver. Will compare the headers ? 

I had "Content-Type" then looked into WireHTTP.php where it's listed everywhere in lowercase, eg:

<?php

public function post($url, $data = array(), array $options = array()) {
		if(!isset($this->headers['content-type'])) $this->setHeader('content-type', 'application/x-www-form-urlencoded; charset=utf-8');
		return $this->send($url, $data, 'POST', $options);
	}

 

Link to comment
Share on other sites

  • psy changed the title to [solved] WireHTTP POST sending application/json data problem

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...