Sending files in curl request with header application-json - json

I am trying to send data in json format in curl request. so my body is like this
$body = json_encode($array);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($body),
'Content-Md5: ' . base64_encode(md5($body, true))
));
I can set content header this way --header "Content-Type: application/json" But when my content body will have files to be sent, will content type header application/json work?
Do i need to change the content-type header if my body has file in it?

No and yes, if you are talking about simulating a browser to "select" files and "upload" them to the server then the header will change to
Content-Type: multipart/form-data;
if on the other hand you are talking about using text files in place of long strings on the command line then no.
Read the notes in the answers at send/post xml file using curl command line

Related

How can I retrieve multiple id from api in one request?

This's API request.
curl --location --request POST 'http://1455.api.123/xx' \
--header 'ApiPass: *******\
--header 'Content-Type: application/json' \
--data-raw '{
"jsonrpc": "2.0",
"id": "null",
"method": "person",
"params": {
"id": 15 // user ID in DB
}
}'
I'm use this code for call request.
public function call_data($id){
$apiKey = '***********';
$apiUrl = 'http://1455.api.123/xx';
$message = json_encode(
array('jsonrpc' => '2.0', 'id' => 'null', 'method' => 'person', 'params' => array('id'=>$id));
);
//$sign = hash_hmac('sha512', $message, $apiSecret);
$requestHeaders = [
'ApiPass:' . $apiKey,
'Content-type: application/json'
];
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
$response = curl_exec($ch);
curl_close($ch);
$arrayData = json_decode($response,true);
$arrayDataUsers = $arrayData;
return $arrayDataUsers;
}
How can I retrieve multiple id from api in once request where i don't want to use loop call_data()?
Note. One request for this code has load time about 0.5sec.
It depends on what capabilities the API provides you. If there is any API that allows you to access multiple IDs at once then you can use it, otherwise unfortunately you'll have to resort to loop only.
If you want to increase the speed of retrieving the results, you might try looking into parallel retrieval of the data but it totally depends on your use case on how you are using the user data ( or if the API limits your parallel requests or not. )

LWP response JSON values are empty

I'm trying to run GET method using LWP and CURL (unix command) to get the content in JSON format, I'm seeing the complete content only in CURL command but the LWP response is showing valid JSON but with empty values.
REQUEST
LWP
my $ua= LWP::UserAgent->new();
my $host='https://sample.com/iersiefhsiof';
$ua->default_header('Content-Type' => 'application/json');
$ua->default_header('Authorization' => 'XXXXXXXXXXXXXXxx');
$ua->default_header('Accept' => 'application/json');
my $response=$ua->get($host);
$res=$response->content();
print ($res);
CURL
curl -H "Accept: application/json" -H "Content-Type: application/json" -H 'Authorization:XXXXXXXXXXXXXXX' -ikL 'https://sample.com/iersiefhsiof'
RESPONSE
LWP
{
"id":"",
"state":"",
"category":"",
"severity":"",}'`
CURL
`{"id":"iersiefhsiof","state":"open","category":"App","severity":"minor",}'`
Please help me to understand what I'm missing in LWP request to get the complete response content.
It is fixed now !
As per Header.pm , I should use ":" for custom header field name , if I'm not using that then it is converting the first characters as Uppercase and hence the header is missed.
unless ($field =~ /^:/) {
$field =~ tr/_/-/ if $TRANSLATE_UNDERSCORE;
my $old = $field;
$field = lc $field;
unless($standard_case{$field} || $self->{'::std_case'}{$field}) {
# generate a %std_case entry for this field
**$old =~ s/\b(\w)/\u$1/g;**
$self->{'::std_case'}{$field} = $old;
}
}
Refer: https://github.com/libwww-perl/HTTP-Message/blob/master/lib/HTTP/Headers.pm
':x-inf-route-key'=>'GetID'
Thanks :)

Autodesk Forge token reauthorization command doesn't recognize parameters

I am using Laravel / PHP on the back end to communicate with the Forge system. To establish an initial token, I am using the guzzle tool kit. This works fine.
// Get environment variables
$FusionID = getenv('THISID');
$FusionSecret = getenv('THISSECRET');
// Make call to get token with authorization code, client id, and secret
$client = new Client(); //GuzzleHttp\Client
$response = $client->request('POST', 'https://developer.api.autodesk.com/authentication/v1/gettoken', [
'form_params' => [
'grant_type' => 'authorization_code',
'code' => $authCode,
'client_id' => $FusionID,
'client_secret' => $FusionSecret,
'redirect_uri' => 'https://www.example.com/redirect',
'scope' => array('data'=>'create', 'data'=>'read')
]
]);
$body = $response->getBody();
$obj = json_decode($body);
For the numerous other commands, the guzzle protocol seems to have issues so I have been using the straight curl commands. However, I can't seem to get either to work for the refresh token.
I have verified that the variables below have the proper data, but I get the error that
"developerMessage":"The required parameter(s) client_id,client_secret,grant_type not present in the request","userMessage":"","errorCode":"AUTH-008",
I am not sure what to do. Both the guzzle method and the curl method do not seem to be working for me.
$thumbData = '{"client_id":"'.$FusionID.'",
"client_secret":"'.$FusionSecret.'",
"grant_type":"refresh_token",
"refresh_token":"'.$userInfo->refresh_token.'"}';
$url = 'https://developer.api.autodesk.com/authentication/v1/refreshtoken';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $thumbData );
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
$response = curl_exec ($ch);
$err = curl_error($ch);
curl_close ($ch);
The way you post x-www-form-urlencoded data with Guzzle looks fine so that leaves the question to be whether your Guzzle version is 6+ otherwise use body instead of form_params as your payload option.
With cURL you request body should be delimited by & in x-www-form-urlencoded format like below instead of `json:
curl_setopt($ch, CURLOPT_POSTFIELDS,
"client_id=sb233&client_secret=2333&...");

arabic in json not display propeplay like "u0633\u0645\u0647"

I'm working on an project that fetch the arabic news from some server that use API to send news to android application and put it to my server.
I have created JSON POST page php and that working fine with me (fetch all i news i need it) only issue with the Arabic Characters and i have add charset=UTF-8 two time as shows in below code
As a result of this code, the output something like : "u0633\u0645\u0647 \u0627\u0644\u0644" since it should be something like "موقع الاخبار على مدار اليوم".
from that application the Arabic characters are displayed properly and I'm sure that they use UTF-8 as charset.
What could be the issue is?
btw i have do some changing header charset by using UTF-16 and UTF-32 instead of UTF-8 and they characters are changed as well to somrhing like Korian characters
$data_string = '{"para":{"pze":"2","date":"2014-06-16 13:55:17","did":"38","la":"ar","page":1,"token":"class","sub":"13"},"req":"a\/get_aet"}';
$ch = curl_init('http://NEWSWEBSITE.SOMETHING/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=UTF-8',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
header('Content-Type: application/json; charset=UTF-8');
print_r( $result);
`

curl example of file download doesn't work

If I follow the box api 2.0 curl example to get the metadata of a file, I get the information. When I append /data to the url to download the file, curl says:
curl: (52) Empty reply from server
I did this with two files, both text files, same result.
The system here is OpenBSD 5.0.
In python 3, the same request raises an exception that says that the reply from the server contained a status line that is empty.
I had the same issue. The problem is that you need the CURLOPT_FOLLOWLOCATION option set to true. Box will execute a redirection from the API call to the actual file. Without it, it will return an empty response.
An empty response should be returned in the event that the file itself is empty. If, for instance, the two text files don't have any text in them, no text will be returned i.e. this appears to be expected behavior.
I'm getting the same issue. I have uploaded a file successfully, retrieved the file ID, then when I try to download the file, nothing happens. Like the original poster mentioned, if I take off the "/data" portion of the URL, then I can get all of the info back about the file successfully.
Here is my "download code" that gets called from a form with a simple "Download File" button for that particular file ID.
$boxkey = "ThisIsMyAPIKey";
$auth_token = $_POST['auth_token'];
$url = "https://www.box.com/api/2.0/files/".$_POST['file_id']."/data";
$header = array("Authorization: BoxAuth api_key=".$boxkey."&auth_token=".$auth_token);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_exec($ch);
curl_close($ch);
$url = "https://api.box.com/2.0/files/$fileId/content?access_token=$accessToken";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($ch);
curl_close($ch);