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);
Related
use LWP::UserAgent;
use File::Slurp;
use warnings;
use strict;
my $baseUrl = 'xxxxx';
my $accessToken = 'xxxxx';
my $shelfGuid = 'xxxxx';
my $url = $baseUrl . 'yyyy';
my $sourceFile = '/home/example.png';
my $destFile = 'example.png';
my $ua = LWP::UserAgent->new;
$ua->default_header( 'authorization' => "bearer $accessToken" );
my $response = $ua->post($url,
'Content_Type' => 'form-data',
Content => [
file => [
name => $sourceFile,
filename => $destFile,
Content_Type => 'image/png'
],
model => { ShelfGuid => $shelfGuid }
]
);
print $response;
Getting this error - Can't open file name: No such file or directory at /usr/share/perl5/LWP/UserAgent.pm line 419.
Tried a whole day without any progress. Help much appreciated. Thanks.
It's trying to open a file named name. Replace
file => [ name => $sourceFile, filename => $destFile, Content_Type => 'image/png' ]
with
file => [ $sourceFile, $destFile, Content_Type => 'image/png' ]
Unrelated, the value of the other field looks wrong too.
model => { ShelfGuid => $shelfGuid }
The value should be a string, or an array ref for a file upload, but not a hash ref.
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.
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';
[....]
I am trying to post a file uploaded in drupal form to another server through a post request using drupal_http_request.
I am not sure where am I making a mistake but the file doesnot seem to get posted. What should I be doing.?
I use the following code.
$options = array(
'method' => 'POST',
'data' => drupal_http_build_query($data),
'timeout' => $connect_ariba_values['timeout'],
'headers' => array('Content-Type' => 'multipart/form-data'),
);
$response = drupal_http_request($url, $options);
multipart/form-data doesnot seem to work.
Source: https://drupal.org/user/194073
<?php
$boundary = md5(uniqid());
$post_data = array(
'name' => 'Ayesh',
'file' => '/var/www/test/test.png',
);
$options = array(
'method' => 'POST',
'data' => multipart_encode($boundary, $post_data),
'timeout' => $connect_ariba_values['timeout'],
'headers' => array('Content-Type' => "multipart/form-data; boundary=$boundary"),
);
$response = drupal_http_request($url, $options);
// Function to encode text data.
function multipart_enc_text($name, $value){
return "Content-Disposition: form-data; name=\"$name\"\r\n\r\n$value\r\n";
}
// Function to multipart encode a file from a give path.
function multipart_enc_file($path){
if (substr($path, 0, 1) == "#") $path = substr($path, 1);
$filename = basename($path);
$mimetype = "application/octet-stream";
$data = "Content-Disposition: form-data; name=\"file\"; filename=\"$filename\"\r\n"; // "file" key.
$data .= "Content-Transfer-Encoding: binary\r\n";
$data .= "Content-Type: $mimetype\r\n\r\n";
$data .= file_get_contents($path) . "\r\n";
return $data;
}
// base function to encode a data array.
function multipart_encode($boundary, $params){
$output = "";
foreach ($params as $key => $value){
$output .= "--$boundary\r\n";
if ($key == 'file'){
$output .= multipart_enc_file($value);
} else $output .= multipart_enc_text ($key, $value);
}
$output .="--$boundary--";
return $output;
}
In the server, file will be available in $_FILES['file'], and other POST data will be available in their relevant keys.
I didn't test the code. I just found the code in drupal forum, changed it to work with Drupal 6 and 7.
I once wrote a simple 'crawler' to download http pages for me in JAVA.
Now I'm trying to rewrite to same thing to Perl, using LWP module.
This is my Java code (which works fine):
String referer = "http://example.com";
String url = "http://example.com/something/cgi-bin/something.cgi";
String params= "a=0&b=1";
HttpState initialState = new HttpState();
HttpClient httpclient = new HttpClient();
httpclient.setState(initialState);
httpclient.getParams().setCookiePolicy(CookiePolicy.NETSCAPE);
PostMethod postMethod = new PostMethod(url);
postMethod.addRequestHeader("Referer", referer);
postMethod.addRequestHeader("User-Agent", " Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13");
postMethod.addRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8");
postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
String length = String.valueOf(params.length());
postMethod.addRequestHeader("Content-Length", length);
postMethod.setRequestBody(params);
httpclient.executeMethod(postMethod);
And this is the Perl version:
my $referer = "http://example.com/something/cgi-bin/something.cgi?module=A";
my $url = "http://example.com/something/cgi-bin/something.cgi";
my #headers = (
'User-Agent' => 'Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13',
'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Referer' => $referer,
'Content-Type' => 'application/x-www-form-urlencoded',
);
my #params = (
'a' => '0',
'b' => '1',
);
my $browser = LWP::UserAgent->new( );
$browser->cookie_jar({});
$response = $browser->post($url, #params, #headers);
print $response->content;
The post request executes correctly, but I get another (main) webpage. As if cookies were not working properly...
Any guesses what is wrong?
Why I'm getting different result from JAVA and perl programs?
You can also use WWW::Mechanize, which is a wrapper around LWP::UserAgent. It gives you the cookie jar automatically.
You want to be creating hashes, not arrays - e.g. instead of:
my #params = (
'a' => '0',
'b' => '1',
);
You should use:
my %params = (
a => 0,
b => 1,
);
When passing the params to the LWP::UserAgent post method, you need to pass a reference to the hash, e.g.:
$response = $browser->post($url, \%params, %headers);
You could also look at the request you're sending to the server with:
print $response->request->as_string;
You can also use a handler to automatically dump requests and responses for debugging purposes:
$ua->add_handler("request_send", sub { shift->dump; return });
$ua->add_handler("response_done", sub { shift->dump; return });
I believe it has to do with $response = $browser->post($url, #params, #headers);
From the doc of LWP::UserAgent
$ua->post( $url, \%form )
$ua->post( $url, \#form )
$ua->post( $url, \%form, $field_name => $value, ... )
$ua->post( $url, $field_name => $value,... Content => \%form )
$ua->post( $url, $field_name => $value,... Content => \#form )
$ua->post( $url, $field_name => $value,... Content => $content )
Since your params and headers are as hashes, I would try this:
my $referer = "http://example.com/something/cgi-bin/something.cgi?module=A";
my $url = "http://example.com/something/cgi-bin/something.cgi";
my %headers = (
'User-Agent' => 'Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13',
'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Referer' => $referer,
'Content-Type' => 'application/x-www-form-urlencoded',
);
my %params = (
'a' => '0',
'b' => '1',
);
my $browser = LWP::UserAgent->new( );
$browser->cookie_jar({});
$response = $browser->post($url, \%params, %headers);