How to send data by XML file via an API integration to the server

Asked

Viewed 2,619 times

2

I am using the Codeigniter Framework and trying to do a system integration via API using XML.

I have to send a file with XML parameters to a server via post. Basically the server has to receive a string with data=xml content.

I tested with Advanced Rest Client (Chrome extension that simulates a POST upload) and worked perfectly, IE, the server is OK.

when I play in PHP code it fails to send XML and returns error 400 (bad request).

Does anyone have any tips?

Follows code:

<?php
$query = $this -> db -> query('SELECT token FROM configuracao LIMIT 1');
$row = $query -> row_array();
$token = $row['token'];

$conteudoXML= "data=";
$conteudoXML.= "<schedule>";
$conteudoXML.= "<alternativeIdentifier>1234567</alternativeIdentifier>";
$conteudoXML.= "<observation>1234567</observation>";
$conteudoXML.= "<agent><id>220876</id></agent>";
$conteudoXML.= "<serviceLocal><alternativeIdentifier>teste</alternativeIdentifier></serviceLocal>";
$conteudoXML.= "<activitiesOrigin>4</activitiesOrigin>";
$conteudoXML.= "<date>2015-11-25</date>";
$conteudoXML.= "<hour>00:00</hour>";
$conteudoXML.= "<activityRelationship>";
$conteudoXML.= "<activity><alternativeIdentifier>corretiva</alternativeIdentifier></activity>";
$conteudoXML.= "</activityRelationship>";
$conteudoXML.= "</schedule>";

$url = "http://api.umov.me/CenterWeb/api/$token/schedule.xml";
$xml_str = $conteudoXML;


$post_data = array('xml' => $xml_str);
$stream_options = array(
'http' => array(
    'method'  => 'POST',
    'header'  => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
    'content' =>  http_build_query($post_data)));

$context  = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);
?>
  • Do you want to send data, or do you want to consume the server data? It was not clear to me.

  • In fact happens the 2, first he sends a request, then he looks for the result (whether it worked out or not). I was able to solve with the crul

1 answer

1

I managed to solve...

I changed the method to Curl (I had to install it because my server was not available).

In the end it was like this:

//setting the curl parameters.
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);

    if (curl_errno($ch)) 
{
    // moving to display page to display curl errors
      echo curl_errno($ch) ;
      echo curl_error($ch);
} 
else 
{
    //getting response from server
    $response = curl_exec($ch);
     print_r($response);
     curl_close($ch);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.