best practice Richiesta parser per Servizi 3.x
Domanda
Quando si crea un endpoint del servizio è possibile attivare varie parser richiesta (application / json, application / x-www-form-urlencoded, multipart / form-data ...) Come devo decidere se inviare la richiesta utilizzando JSON vs form-data?
La maggior parte del "nodo di creare" esempi che ho visto fare qualcosa di simile (credo che questo usi form-data):
//create a node
$node_data = array(
"title"=>"DHC Tool 01",
"type"=>"item",
"status"=>false, //ensure unpublished
"language" => "und", //lanugage neutral
"field_webpage"=>array(
"und"=>array(
0=>array("url"=>"http://berkeley.edu",)
)
)
);
// Use JSON
// $node_data = '{"title":"Tool Unpublished 10","type":"item","status":false,"language":"und","field_webpage":{"und":[{"url":"http:\/\/berkeley.edu"}]}}';
$options['data'] = http_build_query($node_data, '', '&');
$response = drupal_http_request($base_url . '/node', $options);
C'è qualche vantaggio per l'invio del nodo di creare richiesta utilizzando JSON?
Come sarebbe il codice di cui sopra essere modificato per utilizzare JSON?
Grazie!
Soluzione
Questo codice invierà una richiesta codificata come JSON:
function toolreq_test_create() {
$base_url = 'http://example.com/dirt';
$options = toolreq_service_login(); //this yields $options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
if (!is_array($options)) {
print "error<p>";
return;
}
//create a node
$node_data = array(
'title' => 'DHC Tool 03',
'type' => 'item',
'status' => FALSE, //ensure unpublished
'language' => 'und', //lanugage neutral
'field_webpage' => array(
'und' => array(
0 => array('url' => 'http://berkeley.edu',)
)
)
);
//use json
$options['headers']['content-type'] = "application/json";
$options['method'] = 'POST';
$options['data'] = json_encode($node_data);
$request = drupal_http_request($base_url . '/node', $options);
if ($request->error) {
print ("Error doing http request");
print '<pre>' . var_dump($request) . '</pre>';
}
else {
print ("Success doing http request");
print '<pre>' . var_dump(json_decode($response->data)) . '</pre>';
}
}
Quando si considera il formato migliore per la vostra richiesta tenere a mente:
- JSON è un formato utile per le applicazioni Ajax perché ti permette di convertire tra oggetti JavaScript e valori di stringa in fretta. ref: http://www.ibm.com/developerworks/ web / library / wa-ajaxintro11 / index.html
- https://stackoverflow.com/questions/4007969 / application-x-www-form-urlencoded-o-multipart-form-data
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a drupal.stackexchange