QLineEdit *nameEdit = new QLineEdit(this);
QPushButton *btn = new QPushButton(QStringLiteral("确定"),this);
btn->move(nameEdit->rect().bottomLeft());
connect(btn,&QPushButton::clicked,[nameEdit]{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl){
struct curl_slist *headers = nullptr;//Content-Type:application/json;charset=UTF-8
headers = curl_slist_append(headers,"Content-Type:application/json;charset=UTF-8");
// headers = curl_slist_append(headers,"Accept-Encoding:gzip, deflate");
// headers = curl_slist_append(headers,"Accept-Language:zh-CN,en,*");
// headers = curl_slist_append(headers,"User-Agent:Mozilla/5.0");
// headers = curl_slist_append(headers, "Expect:"); //解除分1024个字节分次发送的限制
curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headers);
curl_easy_setopt(curl, CURLOPT_POST, 1); //作用POST
curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1:8000"); // 指定url
QString str = nameEdit->text();
std::string arr = str.toStdString(); //这一步必须有,不能用连调的形式 str.toStdString().data()是不行的;
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, arr.data()); // 指定post内容,也可以是arr.c_str()
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, arr.size());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, response);
QByteArray responseArr;
curl_easy_setopt(curl,CURLOPT_WRITEDATA, &responseArr);
curl_easy_setopt(curl, CURLOPT_TIMEOUT,3);
res = curl_easy_perform(curl);
if(res != CURLE_OK){
qDebug() << curl_easy_strerror(res);
}else{
qDebug() << "Curl received " << QString(responseArr);
QJsonDocument jsDoc;
QJsonParseError jserror;
jsDoc = QJsonDocument::fromJson(responseArr,&jserror);
QJsonObject jsObj = jsDoc.object();
qDebug() << jsObj["res"].toString();
}
curl_easy_cleanup(curl);
}
});
python服务器端需要使用
# -*- coding: utf-8 -*-
UTF-8编码