Pergunta

When you create a service endpoint you can enable various request parsers (application/json, application/x-www-form-urlencoded, multipart/form-data...) How should I decide whether to send the request using JSON vs form-data?

Most of the "node create" examples I've seen do something like this (I think this uses 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);

Is there any advantage to sending the node create request using JSON?

How would the above code be modified to use JSON?

Thanks!

Foi útil?

Solução

This code will send a request encoded as 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>';
   }
 }

When considering the best format for your request keep in mind:

Licenciado em: CC-BY-SA com atribuição
Não afiliado a drupal.stackexchange
scroll top