I'm developing a basic application in Qt that retrieves data from Parse.com using the REST API. I went through some class references and the cURL manual but it's still not clear how you set the request parameters. For example, I'd like to authenticate a user. Here's the curl example provided by Parse:
curl -X GET \
-H "X-Parse-Application-Id: myappid" \
-H "X-Parse-REST-API-Key: myapikey" \
-G \
--data-urlencode 'username=test' \
--data-urlencode 'password=test' \
https://api.parse.com/1/login
I set the url and the headers like this
QUrl url("https://api.parse.com/1/login");
QNetworkRequest request(url);
request.setRawHeader("X-Parse-Application-Id", "myappid");
request.setRawHeader("X-Parse-REST-API-Key", "myapikey");
nam->get(request);
which worked fine when there were no parameters, but what should I use to achieve the same as curl does with the --data-urlencode switch?
Thanks for your time
Unfortunately, QUrl::addQueryItem() is deprecated in qt5 but starting from there I found the QUrlQuery class which has an addQueryItem() method and can produce a query string that is acceptable for QUrl's setQuery() method so it now looks like this and works fine:
QUrl url("https://api.parse.com/1/login");
QUrlQuery query;
query.addQueryItem("username", "test");
query.addQueryItem("password", "test");
url.setQuery(query.query());
QNetworkRequest request(url);
request.setRawHeader("X-Parse-Application-Id", "myappid");
request.setRawHeader("X-Parse-REST-API-Key", "myapikey");
nam->get(request);
Thanks for the tip Chris.
I believe QUrl::addQueryItem() is what you're looking for
QUrl url("https://api.parse.com/1/login");
url.addQueryItem("username", "test");
url.addQueryItem("password", "test");
...
Try to use QtCUrl. It's easy, if you are familiar with curl.
QtCUrl cUrl;
QUrl url("https://api.parse.com/1/login");
url.addEncodedQueryItem("username", "test");
url.addEncodedQueryItem("password", "test");
QtCUrl::Options opt;
opt[CURLOPT_URL] = url;
QStringList headers;
headers
<< "X-Parse-Application-Id: myappid"
<< "X-Parse-REST-API-Key: myapikey"
opt[CURLOPT_HTTPHEADER] = headers;
QString result = cUrl.exec(opt);
Related
How to call a REST API from javascript with ajax or XMLHttpRequest to upload a file using
Content-Type: multipart/form-data.
File content is in binary format, but the API which I am calling has following request format:
Authorization: Bearer <>
Content-Type: multipart/form-data
I am using following code segment to upload the file content:
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", requestUrl);
xmlHttp.setRequestHeader("Authorization", "Bearer " + token);
xmlHttp.setRequestHeader("Content-Type", "multipart/form-data");
xmlHttp.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xmlHttp.send(formData);
Where formData is the filecontent in binary format. Please suggest if this is the right way or should be handled differently.The file type I am using is an IFC file. And the error I am receiving is media-type not supported
Thanks!
For uploading files to Autodesk Forge (A360), the following curl command works in a Unix-like terminal:
curl -v 'https://developer.api.autodesk.com/oss/v2/buckets/$bucket_name/objects/$filename.ifc' \
-X 'PUT' \
-H 'Authorization: Bearer $token' \
-H 'Content-Type: text/plain; charset=UTF-8' \
-T '$filename.ifc'
since IFC files are text (ASCII) files and not binary files.
Using the same Content-Type might do the trick in your case.
Hope it helps.
i am new to using curl and I am trying to execute a https post request using curl. and it doest seem to work like other json post requests so i was hoping someone can explain this to me
I am not sure if i understood your answer well enough but you can take a look at this Package or this one the latter one provides provides more flexibility and features like Interceptors etc.
You can use this package Curl https://pub.dev/packages/curl
example code
import 'package:curl/curl.dart';
import 'package:http/http.dart';
final req1 = new Request("GET", "https://exyui.com/endpoint");
print(toCurl(req1));
// will print out:
// curl 'https://exyui.com/endpoint' --compressed --insecure
final req2 = new Request("PUT", "https://exyui.com/endpoint");
req2.body = "This is the text of body😅, \\, \\\\, \\\\\\";
print(req2);
// will print out:
// curl 'https://exyui.com/endpoint' -X PUT -H 'content-type: text/plain; charset=utf-8' --data-binary \$'This is the text of body\\ud83d\\ude05, \\, \\\\, \\\\\\' --compressed --insecure
final req3 = new Request("POST", "https://exyui.com/endpoint");
final part1 = "This is the part one of content";
final part2 = "This is the part two of content😅";
final expectQuery = "part1=This%20is%20the%20part%20one%20of%20content&part2=This%20is%20the%20part%20two%20of%20content%F0%9F%98%85";
req3.bodyFields = {
"part1": part1,
"part2": part2,
};
print(toCurl(req3));
I am confusing when I want to post a image file to server. With a clear post, I can just use QHttpMultiPart ,and it works fine. But this time I want to add some params, the server just don't get them.
I have searched for days , But no solution is found.
The code goes like this:
QUrl url("http://192.168.1.211/v1");
QUrlQuery query;
//following params are what i want to add
query.addQueryItem("app_name", "pc");
query.addQueryItem("ip", "192.168.1.110");
query.addQueryItem("dev_os","android");
query.addQueryItem("dev_os_ver","11.4.1");
query.addQueryItem("dev_model",testEquip);
query.addQueryItem("latitude","23.137466");
query.addQueryItem("longitude","113.352425");
query.addQueryItem("user_id","1");
query.addQueryItem("nickname","nick");
query.addQueryItem("sex","1");
query.addQueryItem("headimgurl","http://some.com/");
url.setQuery(query);
QNetworkRequest req;
req.setUrl(url);
req.setRawHeader("X-Api-Key","JDZBNH3HDFI823AISDU9SF32IRJ");
QHttpMultiPart *multiPart=new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart imagePart;
imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
imagePart.setHeader(QNetworkRequest::ContentDispositionHeader,QVariant("form-data; name=\"image\"; filename=\""+filename+"\""));
QFile *file=new QFile(path);
file->open(QIODevice::ReadOnly);
imagePart.setBodyDevice(file);
file->setParent(multiPart);
multiPart->append(imagePart);
QNetworkAccessManager *manager=new QNetworkAccessManager();
QNetworkReply *reply=manager->post(req,multiPart);
multiPart->setParent(reply);
The response code shows no params have been accessed. So what is the right way to add these params?
I’m playing with GitHub web hooks and I want to use curl to post some sample JSON. The request is supposed to contain a payload POST parameter with the JSON string as a value. As an example, this works:
$ curl --form payload='{"foo":1}' http://somewhere
But I need to read the JSON from a file (say foo.json). Replacing the JSON string by #foo.json posts the payload in the request body:
--------------------------8d0c6d3f9cc7da97
Content-Disposition: form-data; name="payload"; filename="foo.json"
Content-Type: application/octet-stream
{'foo':1}
--------------------------8d0c6d3f9cc7da97--
That’s not really what I want, I need the payload to be passed as a parameter. How do I do that?
Maybe silly but try this:
cat foo.json | xargs -I % curl --form payload='%' http://example.com
Just wrote this little thing and it worked:
var=`cat some.json` && curl --form payload="$var" http://lvh.me/test/index.php
Here’s an alternative Perl testing script. Pass the target URL as the first argument, feed the JSON to STDIN:
#!/usr/bin/env perl
use strict;
use warnings;
use LWP;
my $target = shift #ARGV or die "Need a target URL";
my $ua = LWP::UserAgent->new;
my $payload = do { local $/; <STDIN> };
my $response = $ua->post($target, { payload => $payload });
print $response->as_string;
I hava a problem of uploading .txt file to my java servlet server using Qt.
I spent 5 days on that and tried a lot of solutions. But none of them worked. Does anyone can help me?
The problem is that the Qt code can work without error. But the server didn't receive anything by the httprequest from Qt.
This is one solution in Qt:
QFile file("dataToSend.txt");
nam = new QNetworkAccessManager(this);
QObject::connect(nam, SIGNAL(finished(QNetworkReply*)),
this, SLOT(finishedSlot(QNetworkReply*)));
QNetworkRequest r(QUrl("http://localhost:9999/server"));
QString bound="---------------------------723690991551375881941828858";
QByteArray data(QString("--"+bound+"\r\n").toAscii());
data += QString("--" + bound + "\r\n").toAscii();
data += "Content-Disposition: form-data; name=\"file\"; filename=\""+file.fileName()+"\"\r\n";
data += "Content-Type: text/plain\r\n\r\n";
file.open(QIODevice::ReadOnly);
data += file.readAll();
data += "\r\n";
data += QString("--" + bound + "\r\n").toAscii();
r.setRawHeader(QString("Content-Type").toAscii(),QString("multipart/form-data; boundary=" + bound).toAscii());
r.setRawHeader(QString("Content-Length").toAscii(), QString::number(data.length()).toAscii());
reply = nam->post(r,data);
reply=nam->get(r);
This is another solution, it is not wokring neither:
nam = new QNetworkAccessManager(this);
QObject::connect(nam, SIGNAL(finished(QNetworkReply*)),
this, SLOT(finishedSlot(QNetworkReply*)));
QFile *file=new QFile("dataToSend.txt");
QNetworkRequest request(QUrl("http://localhost:9999/server"));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-streamd");
if(!file->open(QIODevice::ReadOnly)){
qDebug("%s\n",qPrintable("can't open the file!"));
return;
}
// post data to server
reply= nam->post(request,file);
file->setParent(reply);
reply=nam->get(request);
you cannot post() something to a server and a line below do a get() expecting to see the file.
Usually you have to post, wait until post is finished, and than you can see modification..
here there are lots of link you can use to do things right