Box API bad request when uploading image - qt

According to box API to upload a file this is the curl command:
curl https://upload.box.com/api/2.0/files/content \
-H "Authorization: Bearer ACCESS_TOKEN" -X POST \
-F attributes='{"name":"tigers.jpeg", "parent":{"id":"11446498"}}' \
-F file=#myfile.jpg
I am trying to upload an image using QT, the following is my code:
QUrl url(QString::fromLatin1("https://upload.box.com/api/2.0/files/content"));
auto* multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart attributes;
attributes.setHeader(QNetworkRequest::ContentDispositionHeader,
QLatin1String("form-data; name=\"attributes\""));
QByteArray postData = QString::fromUtf8("{\"name\":\"%1\",\"parent\":{\"id\":\"%2\"}}").arg(QFileInfo(imgPath).fileName()).arg(id).toUtf8();
attributes.setBody(postData);
multipart->append(attributes);
QFile* file = new QFile(imgPath);
file->open(QIODevice::ReadOnly);
file->setParent(multipart);
QHttpPart imagepart;
imagepart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
imagepart.setHeader(QNetworkRequest::ContentDispositionHeader,QVariant(QString::fromLatin1("form-data; name=\"image\";filename=\"%1\"").arg(QLatin1String(QFileInfo(imgPath).fileName().toUtf8()))));
imagepart.setHeader(QNetworkRequest::ContentLengthHeader, file->size());
imagepart.setBodyDevice(file);
multipart->append(imagepart);
QNetworkRequest netRequest(url);
netRequest.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("multipart/form-data"));
netRequest.setRawHeader("Authorization", QString::fromLatin1("Bearer {%1}").arg(d->o2->token()).toUtf8());
d->reply = d->netMngr->post(netRequest, multipart);
multipart->setParent(d->reply);
When I try to upload the image I get an error saying
Error transferring https://upload.box.com/api/2.0/files/content -
server replied: Bad Request
What am I doing wrong?

Related

R curl sending email with attachments

I am trying to send an email with attachment using R curl.
If I use the command line, the following succeeds in sending an email via curl from from#mail.com to to#mail.com and attaches the file tester.pdf (note authentication is done using SSL and the password would be horsebatterystaple):
BODY="This is the body of the email..."
SUBJECT="Did you get my last email with the reports?"
curl -v \
--url smtp://the-smtp-server:587 \
--ssl-reqd \
--mail-from from#mail.com \
--mail-rcpt to#mail.com \
--user from#mail.com:horsebatterystaple \
-F '=(;type=multipart/mixed' -F "=$BODY;type=text/plain" \
-F "file=#tester.pdf;type=application/pdf;encoder=base64" -F '=)' \
-H "Subject: $SUBJECT" \
-H "From: Myself <from#mail.com>" \
-H "To: Someone Else <to#mail.com>"
Now I want to translate that to R and the R curl package.
It works without attachments when I use this resource, but I cannot find a way to properly emulate the -F (form) flags.
See my attempt below.
There are no form arguments in the curl options (curl::curl_options("form")) and I do not find example code for curl::form_file() or the mimepost option (=> curl::curl_options("mime")).
Any ideas how to make this work?
Note I am not looking for cmd <- "curl -v --url ..."; system(cmd) type solutions if possible...
h <- curl::new_handle(
verbose = TRUE,
url = "smtp://the-smtp-server:587",
use_ssl = 1,
mail_from = "from#mail.com",
mail_rcpt = "to#mail.com",
username = "from#mail.com",
password = "horsebatterystaple"
)
curl::handle_setheaders(h,
"Subject: Hello World",
"From: Myself <from#mail.com>",
"To: Someone Else <to#mail.com>"
)
curl::curl_fetch_memory(handle = h)
Update
After reading through some more documentation, I also found curl::send_email(), therefore my R code is updated to the following, but the attachment still do not work... (see tries as comments):
conf <- list(smpt_server = "...", ...)
verbose <- TRUE
url <- paste0("smtp://", conf$smtp_server, ":", conf$smtp_port)
message <- glue::glue('From: "{conf$name_from}" <{conf$mail_from}>
To: "{conf$name_to}" <{conf$mail_to}>
Subject: {subject}
Hi there,
this is sent from R curl...')
a <- curl::send_mail(
mail_from = conf$mail_from,
mail_rcpt = conf$mail_to,
message = message, smtp_server = url,
use_ssl = TRUE, verbose = verbose,
username = conf$mail_from, password = conf$password,
# mimepost = "file=#tester.pdf;type=application/pdf;encoder=base64"
# mimepost = form_file("tester.pdf", "application/pdf")
)

How do I trigger an Airflow DAG via the REST API?

The 1.10.0 documentation says I should be able to make a POST against /api/experimental/dags//dag_runs to trigger a DAG run, but instead when I do this, I receive an error:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>
To make this work, I figured out that I needed to send an empty JSON string in the body:
curl -X POST \
http://airflow.dyn.fa.disney.com/api/experimental/dags/people_data/dag_runs \
-H 'Cache-Control: no-cache' \
-d '{}'
With the stable API REST/Airflow 2.x, I used:
From CLI:
curl -X POST "http://localhost:8080/api/v1/dags/taskflow_api/dagRuns"
-H "accept: application/json" -H "Content-Type: application/json" \
-d "{}" \
--user "username:password"
With library request https://docs.python-requests.org/en/latest/:
import requests
import json
headers = {
'accept': 'application/json',
'Content-Type': 'application/json'
}
auth = ('username', 'password')
body = {
"conf": {}
}
response = requests.post(url=url,
headers=headers,
auth=auth,
data=json.dumps(body)
)
Note: to check which authentication backend is currently set, see this link https://airflow.apache.org/docs/apache-airflow/stable/security/api.html
I hope it is very useful
Regards

How to resolve octave machine learning submission error?

How to resolve submission error:
curl: (6) Couldn't resolve host 'www-origin.coursera.org'
m = 15
error] submission with curl() was not successful
!! Submission failed: Grader sent no response
Function: submitWithConfiguration>validateResponse
FileName: C:\Users\admin\Desktop\ex7\lib\submitWithConfiguration.m
LineNumber: 158
This error is probably caused because your computer is not able to connect to the internet at the moment.
This is the function working behind collecting the data from the online grader.
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so its probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
Now the statement: "Grader sent no response" is printed when the response is null.
And the response can be null when the computer is not connected.
Hope this is the reason behind your error, if not then let me know.
Matlab?
This steps may helpful:
open file: submitWithConfiguration.m ; and: goto line 131 and 134;
then change:
line131: json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d #- %s', body, url);
line134: json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d #- %s', body, url);
to:
line131: json_command = sprintf('echo jsonBody=%s | curl -k -X POST -s -d #- %s', body, url);
line134: json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -s -d #- %s', body, url);
(both add -s)
it looks like the code is fine and the problem is that your computer can't connect to the internet.
You can simply solve this by using a VPN.
Good luck!

Amazon - Can't request performance report using Advertising API

I'm getting an error using amazon advertising API. I'm currently trying to request performance report using https://advertising-api.amazon.com/v1/campaigns/report.
But the server reply Cannot consume content type
here is my request header and body.
End point : https://advertising-api.amazon.com/v1/campaigns/report
Method Type: POST
Header :
{
Authorization: 'Bearer xxxxxx',
Amazon-Advertising-API-Scope: '11111111111',
Content-Type: 'application/json'
}
Body :
{
campaignType:'sponsoredProducts',
reportDate:'20180320',
metrics:'impressions,clicks'
}
I think I did everything correctly as API document but it says
{
"code": "415",
"details": "Cannot consume content type"
}
Please help me.
Try this way
curl -X POST \
https://advertising-api.amazon.com/v1/campaigns/report \
-H 'Amazon-Advertising-API-Scope: REPLACE_YOUR_PROFILE_ID' \
-H 'Authorization: REPLACE_YOUR_ACCESS_TOKEN' \
-H 'Cache-Control: no-cache' \
-H 'Content-Type: application/json' \
-H 'Host: advertising-api.amazon.com' \
-H 'cache-control: no-cache' \
-d '{
"campaignType": "sponsoredProducts",
"metrics": "impressions,clicks",
"reportDate": "20181101"
}
And you will get a response like
{
"reportId": "amzn1.clicksAPI.v1.p1.......",
"recordType": "campaign",
"status": "IN_PROGRESS",
"statusDetails": "Report is being generated."
}
You can put this curl command in Postman also.
I think your Body may be missing a parameter. When I successfully make a similar POST I need my body to have at least what you have written as well as the segment type. Try adding this to your body:
{
campaignType:'sponsoredProducts',
reportDate:'20180320',
metrics:'impressions,clicks'
segment:'query'
}
Just copy the body from the documentation and paste it in the raw area (of postman) and choose JSON format. For me it works fine.

How do I POST XML data with curl

I want to post XML data with cURL. I don't care about forms like said in How do I make a post request with curl.
I want to post XML content to some webservice using cURL command line interface. Something like:
curl -H "text/xml" -d "<XmlContainer xmlns='sads'..." http://myapiurl.com/service.svc/
The above sample however cannot be processed by the service.
Reference example in C#:
WebRequest req = HttpWebRequest.Create("http://myapiurl.com/service.svc/");
req.Method = "POST";
req.ContentType = "text/xml";
using(Stream s = req.GetRequestStream())
{
using (StreamWriter sw = new StreamWriter(s))
sw.Write(myXMLcontent);
}
using (Stream s = req.GetResponse().GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
MessageBox.Show(sr.ReadToEnd());
}
-H "text/xml" isn't a valid header. You need to provide the full header:
-H "Content-Type: text/xml"
I prefer the following command-line options:
cat req.xml | curl -X POST -H 'Content-type: text/xml' -d #- http://www.example.com
or
curl -X POST -H 'Content-type: text/xml' -d #req.xml http://www.example.com
or
curl -X POST -H 'Content-type: text/xml' -d '<XML>data</XML>' http://www.example.com
It is simpler to use a file (req.xml in my case) with content you want to send -- like this:
curl -H "Content-Type: text/xml" -d #req.xml -X POST http://localhost/asdf
You should consider using type 'application/xml', too (differences explained here)
Alternatively, without needing making curl actually read the file, you can use cat to spit the file into the stdout and make curl to read from stdout like this:
cat req.xml | curl -H "Content-Type: text/xml" -d #- -X POST http://localhost/asdf
Both examples should produce identical service output.
Have you tried url-encoding the data ? cURL can take care of that for you :
curl -H "Content-type: text/xml" --data-urlencode "<XmlContainer xmlns='sads'..." http://myapiurl.com/service.svc/
You can try the following solution:
curl -v -X POST -d #payload.xml https://<API Path> -k -H "Content-Type: application/xml;charset=utf-8"

Resources