I need to add the type of headers to the guzzle request below, but cannot figure out how to put it in without getting an error
This is what I want to add :
$command->set('command.headers', array('content-type' => 'application/x-www-form-urlencoded
to this code below:
<?php
$url = "https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = array('color' => 'red');
$response = $client->request('POST', $url, [
'form_params' => $post_data,
'verify' => false
]);
$body = $response->getBody();
dsm($body);
?>
When I needed use the Guzzle at D8 to make a POST I passed the Content-Type like this:
$url = "https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = array('color' => 'red');
$response = $client->request('POST', $url, [
'headers' => ['Content-Type' => 'application/json'],
'body' => rawData($post_data),
]);
$body = $response->getBody()->getContents();
$status = $response->getStatusCode();
A good idea is use the D8 Dependency Injection to pass the HTTP_CLIENT.
Related
I've problems to set header fields for sending requests by Perl modul 'HTTP::Request::Common'.
In subject to the corresponding server I have to set different header fields for my request.
So I want to use a sub 'MakeRequest()'
sub MakeRequest {
my $url = shift;
my $header = shift;
my $content = shift;
my $request = HTTP::Request::Common::POST($url, Header => $header, Content => $content);
# I tried also my $request = HTTP::Request::Common::POST($url, $header, Content => $content);
my $ua = LWP::UserAgent->new;
my $response = $ua->request($request);
return $response;
}
and pass some informations into it my $response = MakeRequest($url, GetRequestHeader(), $content);
sub GetRequestHeader {
my $header = HTTP::Headers->new;
$header->header('Content-Type' => 'application/json; charset=utf-8');
$header->header('accept' => 'application/json');
$header->authorization_basic($username, $password);
return $header;
# I tried this first, but got the same result as shown below
#
# my %header = (
# 'content_type' => 'application/json; charset=utf-8',
# 'authorization_basic' => ($username, $password),
# 'accept' => 'application/json'
# );
# return %header;
}
But all I got from the remote server is this
"Content type 'application/x-www-form-urlencoded' is not supported.
Please use 'application/json; charset=utf-8'."
When I made a print Data::Dumper($request); I get
'_headers' => bless( {
'content-length' => 544,
'user-agent' => 'libwww-perl/6.15',
'header' => bless( {
'content-type' => 'application/json; charset=utf-8',
'authorization' => 'Basic Qxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==',
'accept' => 'application/json'
}, 'HTTP::Headers' ),
'::std_case' => {
'header' => 'Header',
'if-ssl-cert-subject' => 'If-SSL-Cert-Subject'
},
'content-type' => 'application/x-www-form-urlencoded'
}, 'HTTP::Headers' ),
What's my mistake that the 'content-type' isn't overwritten by my header field settings?
According to the documentation:
HTTP::Request::Common::GET $url, Header => Value,...
is the same as
HTTP::Request->new(
GET => $url,
HTTP::Headers->new(Header => Value,...),
)
I think your original approach (the commented) is good, but you assign it the wrong way:
my $header = shift;
my $content = shift;
my $request = HTTP::Request::Common::POST($url, Header => $header, Content => $content);
Here, you create only one header, named Header. You can use the following if you have a HTTP::Headers object:
my $request = HTTP::Request::Common::POST($url, $header->flatten, Content => $content);
If you change GetRequestHeader to return a hash reference (as you have commented, but with return \%header instead of return %header), you can use the following:
my $request = HTTP::Request::Common::POST($url, %$hashref, Content => $content);
Using the code below on D8 to post a form, I get the following error :
cURL error 77: error setting certificate verify locations: CAfile: C:\Program Files (x86)\DevDesktop\common\cert\cacert.pem CApath: none (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
My question is how can I modify this code to not verify or how can I set a certificate so that I won't get this error. thanks
$url = "https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = array('color' => 'red');
$response = $client->request('POST', $url, [
'headers' => ['Content-Type' => 'application/json'],
'body' => rawData($post_data),
]);
$body = $response->getBody()->getContents();
$status = $response->getStatusCode();
this worked for me, I added verify=>false:
$url="jsonplaceholder.typicode.com/posts
$client = \Drupal::httpClient();
$post_data = $form_state->cleanValues()->getValues();
$response = $client->request('POST', $url,
[ 'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
'form_params' => $post_data,
'verify'=>false, ]);
$body = $response->getBody()->getContents();
$status = $response->getStatusCode();
dsm($body);
dsm($status);
I have a problem when trying to create a folder in my OneDrive using the REST API. I'm using following documentation page https://dev.onedrive.com/items/create.htm. I have successfully authenticated and the token is working ok on other endpoints.
I spent now over a day trying every possible URI/method combination on this one but with no success. All other endpoints (directory listing etc.) are OK, just this one is driving me crazy.
If anyone could point me to the error in my approach, any help would be appreciated.
The code below returns error 400 with following message:
{"error":{"code":"invalidRequest","message":"The request is malformed or incorrect."}}
I'm using GuzzlePhp library for the request handling. My code (simplified):
$parentId = '01WZZ7ZY2LNHB75JADQJD3GGUQFSCRRZTQ'; //id to root
$method = "POST";
//none of these does the trick (to be clear, I use only one at the time)
$url = '/_api/v2.0/drive/items/'.$parentId.'/NewFolder'; //put
$url = '/_api/v2.0/drive/items/'.$parentId.'/children'; //put
$url = '/_api/v2.0/drive/items/'.$parentId.'/children'; //post
$url = '/_api/v2.0/drive/root:/NewFolder'; //post
$options = [
'headers' => [
'Authorization' => $token,
'Content-Type' => 'application/json',
'Content-Length'=> 0,
]
'form_params' => [
"name" => "NewFolder",
"folder" => (object)[],
"#name.conflictBehavior" => "fail"
]
];
//Guzzle library sends the code as specified
$res = $this->client->request($method, $url, $options);
The OneDrive API doesn't support form post semantics - the parameters are expected in the body as a JSON encoded blob. I haven't used Guzzle, but something like this should work:
$parentId = '01WZZ7ZY2LNHB75JADQJD3GGUQFSCRRZTQ'; //id to root
$method = "POST";
//none of these does the trick (to be clear, I use only one at the time)
$url = '/_api/v2.0/drive/items/'.$parentId.'/NewFolder'; //put
$url = '/_api/v2.0/drive/items/'.$parentId.'/children'; //put
$url = '/_api/v2.0/drive/items/'.$parentId.'/children'; //post
$url = '/_api/v2.0/drive/root:/NewFolder'; //post
$options = [
'headers' => [
'Authorization' => $token,
'Content-Type' => 'application/json',
'Content-Length'=> 0,
]
'body' =>
'{
"name": "NewFolder",
"folder": { },
"#name.conflictBehavior": "fail"
}'
];
//Guzzle library sends the code as specified
$res = $this->client->request($method, $url, $options);
I'm using drupal7. my drupal_http_request() for get and delete are working fine for authenticated users, but the post and put methods are not working.
The error is :Not Acceptable : Node type is required, and http error code is :406. My code is below:
function ws_form_post_auth() {
$base_url = 'http://localhost/drupalws/api/v1';
$data = array(
'username' => 'student1',
'password' => 'welcome',
);
$data = http_build_query($data, '', '&');
$options = array(
'headers' => array(
'Accept' => 'application/json',
),
'method' => 'POST',
'data' => $data
);
$response = drupal_http_request($base_url . '/user/login', $options);
$data = json_decode($response->data);
// Check if login was successful
if ($response->code == 200) {
$options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
$options['headers']['X-CSRF-Token'] = $data->token;
$data = array(
'title' => 'First forum post',
'type'=> 'forum',
'body'=> array(
'und'=>array(
0=> array(
'value'=>'This is my first forum post via httprequest.'
)
)
)
);
$data = json_encode($data);
$options['data'] = $data;
$options['method'] = 'POST';
$response = drupal_http_request($base_url . '/node', $options);
return $response->status_message;
}
return $response->status_message;
}
I got the solution for my issue,I just missed a Content-Type in Headers.
[....]
if ($response->code == 200) {
$options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
$options['headers']['X-CSRF-Token'] = $data->token;
$options['headers']['Content-Type'] = 'application/json';
[....]
Sugarcrm is providing Restful API support.So how can i check json response using rest client(browser plugin to check restful web services)?.
I am developing a web-app using spring MVC(Restful API).I want to use sugarcrm as my crm module.how can i integrate both?.
I have gone through sugar's documentation about the same ,but I do not have any idea about php biased programming.
can anyone please help me?
Thanks.
run below code, if you have any problem then let me know.
<?php
//Put your Base url
$url = 'yoursugarcrm_url/service/v4_1/rest.php';
// Open a curl session for making the call
$curl = curl_init($url);
// Tell curl to use HTTP POST
curl_setopt($curl, CURLOPT_POST, true);
// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the POST arguments to pass to the Sugar server
$parameters = array(
'user_auth' => array(
'user_name' => 'admin',
'password' => md5('uDje9ceUo89nBrM'),
),
);
$json = json_encode($parameters);
$postArgs = array(
'method' => 'login',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => $json,
);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($curl);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
if ( !is_object($result) ) {
die("Error handling result.\n");
}
if ( !isset($result->id) ) {
die("Error: {$result->name} - {$result->description}\n.");
}
// Get the session id
$sessionId = $result->id;
//echo json_encode(array("sessionId"=>$sessionId));
//Your moduel parameter
//Parameter of the customer
$fullname = $_POST['fullname'];
$password = md5($_POST['password']);
$email_address = $_POST['email_address'];
// My moduel
$parameters = array(
'session' => $sessionId, //Session ID get from session.php
'module' => 'custo_Customers', // Your PackageKey_ModuleName
'name_value_list' => array (
array('name' => 'fullname', 'value' => $fullname),
array('name' => 'email_address', 'value' => $email_address),
array('name' => 'password', 'value' => $password),
),
);
$json = json_encode($parameters); // Json strgin
$postArgs = 'method=set_entry&input_type=JSON&response_type=JSON&rest_data=' . $json;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($curl);
// Convert the result from JSON format to a PHP array
$result = json_decode($response,true);
echo $response;
?>