Http post, get the difference between code sample

A difference, Get and POST methods

Http protocol server interacts with the basic four methods: GET, POST, PUT, DELETE, corresponding to the resource check, change, add, delete four operations.

GET is generally used to get / query resource information, and resource information for updating the general POST

the difference:

  1. After the GET data submitted will be placed URL, in order? URL split and transfer data between the parameters & linked, as EditPosts.aspx name = text1 & id = 12345;? POST method and the data is submitted in the HTTP packet Body
  2. GET submitted the data size is limited (because the browser restrictions on the length of the URL), and the data submitted by the POST method does not limit
  3. GET requires the use Request.QueryString to get the value of a variable, while the POST method to get the value of a variable by Request.Form
  4. Submit a GET data, will bring security problems, such as a landing page, when submitting data via GET, the user name and password will appear in the URL, if the page can be cached or others can access this machine, you can from history record obtain the user ID and password

to sum up:

Relatively large amounts of data - with the post (data packet on Body http)

A small amount of data - with get (after the data on the URL)

Second, data transmitted using POST

Mainly in order to transmit a larger amount of data the client to the server, not the URL length limit

The HTTP post request data in the body, the field in the form fieldname = value as a URL-encoded, each field separated by &

  1. A small amount of data - once a post

Content-Type : application/x-www-form-urlencoded

transfer

Http * m_http = new Http();
QByteArray retData = "";
bool bl = m_http->post(uploadUrl, "", retData, token);
bool Http::post(const QString url,const QString data, QByteArray &ret, const QString token)
{
    QNetworkAccessManager *manager = new QNetworkAccessManager;
    QNetworkReply *reply;
    QNetworkRequest u = QNetworkRequest(QUrl(url));
    u.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-Form-urlencoded");
    QByteArray dataa = data.toUtf8();
    if (token != "")
    {
        u.setRawHeader("x-authentication-token", token.toLatin1());
    }
    u.setHeader(QNetworkRequest::ContentLengthHeader, dataa.length());
    reply = manager->post(u, dataa);
    
    QEventLoop loop; // 使用事件循环使得网络通讯同步进行
    QTimer::singleShot(6000, &loop, SLOT(quit()));
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec(); // 进入事件循环, 直到reply的finished()信号发出, 这个语句才能 //退出    
    
    if (reply->error())
    {
        ret = reply->errorString().toLatin1();
        delete manager;
        return false;
    }
    if (reply->isFinished()) {
        ret = reply->readAll();
        delete manager;
        return  true;
    }
    else {
        delete manager;    
        return false;
    }
}
  1. Large amounts of data - a post - use multipart

Using the attribute "Content-Type" = "multipart / form-data; boundary = ABCD", post once

transfer

Http * m_http = new Http();
QString resultStr = "";
QString m_uploadFileUrl= "对方 URL 路径";
QString path= "D://A.jpg";
m_http->uploadFile(m_uploadFileUrl, path, "pic", resultStr)
bool Http::uploadFile(const QString url, const QString path, const QString param,QString &resultStr)
{
    QString absultePath = path;
    QFile file(absultePath);
    if (!file.exists())
    {
        resultStr = "filepath not exists";
        return false;
    }
    if (!file.open(QIODevice::ReadOnly))
    {    
        resultStr = "open file failed";
        return false;
    }
    QFileInfo fi(absultePath);

    QNetworkAccessManager *accessManager = new QNetworkAccessManager(this);    
    QNetworkReply *reply;
    accessManager->setNetworkAccessible(QNetworkAccessManager::Accessible);
    
    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    // dat 文件;
    if ("dat" == param)
    {
        QHttpPart datPart;
        datPart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain"));

        QString contentDis = tr("form-data; name=\"file\"; filename=\"%1\"").arg(fi.fileName());
        datPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(contentDis));
        datPart.setBody(file.readAll());
        file.setParent(multiPart);
        multiPart->append(datPart);
    }
    // 图片文件;
    else
    {
        QHttpPart imagePart;
        imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/png"));

        QString contentDis = tr("form-data; name=\"file\"; filename=\"%1\"").arg(fi.fileName());
        imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(contentDis));
        imagePart.setBody(file.readAll());
        file.setParent(multiPart);
        multiPart->append(imagePart);

        QHttpPart textPart;
        textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"modelImg\""));
        textPart.setBody("img");
        multiPart->append(textPart);
    }

    multiPart->setBoundary("-----WebKitFormBoundaryE19zNvXGzXaLvS5C");

    QUrl gurl(url);
    QNetworkRequest request(gurl);

    reply = accessManager->post(request, multiPart);

    bool bl = false;

    QEventLoop loop;
    //QTimer::singleShot(40000, &loop, SLOT(quit()));
    connect(accessManager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));
    loop.exec();

    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray jpegData = reply->readAll();
        resultStr = ((QString)jpegData).toUtf8();

        reply->deleteLater();

        QJsonParseError parse_error;
        const QJsonDocument &parse_doc = QJsonDocument::fromJson(jpegData, &parse_error);
        if (parse_error.error == QJsonParseError::NoError)
        {
            const QJsonObject &object = parse_doc.object();
            int status = object.value(QStringLiteral("errorCode")).toInt();

            if (0 == status)
            {
                bl = true;
                qDebug() << "upload success";
            }
            else
            {
                qDebug() << "upload fail";
                resultStr = object.value(QStringLiteral("message")).toString();
            }
        }
        else
        {
            resultStr = QStringLiteral("data not json[") + jpegData;
        }
    }
    else
    {
        qDebug() << "uploadfile error " << reply->error() << reply->errorString();
        resultStr = reply->errorString();
        reply->deleteLater();
    }

    delete accessManager;
    return bl;
}
  1. Large amounts of data - Multiple post

4k using data once each post, the operation times post

Http * m_http = new Http();
QString resultStr = "";
QString m_uploadFileUrl= "对方 URL 路径";
QString path= "D://A.dat";
m_http->uploadFile(m_uploadFileUrl, path, "", resultStr)
bool Http::uploadFile(const QString url, const QString path, const QString param,QString &error)
{
    QString absultePath = path;
    QFile file(absultePath);
    if (!file.exists()) {
        error = "filepath not exists";
        return false;
    }
    if (!file.open(QIODevice::ReadOnly)) {    
        error = "open file failed";
        return false;
    }

    qint64 length = file.size();

    QNetworkAccessManager *accessManager = new QNetworkAccessManager(this);    
    QNetworkReply *reply;
    accessManager->setNetworkAccessible(QNetworkAccessManager::Accessible);

    QUrl gurl(url);
    QNetworkRequest request(gurl);

    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream");
    request.setHeader(QNetworkRequest::ContentLengthHeader, length);

    bool bl = false;

    int64_t pos = 0;// reqUploadPostion(md5, length);
    int64_t postion = pos;
    request.setHeader(QNetworkRequest::LocationHeader, postion);

    while (!file.atEnd())
    {
        file.seek(postion);
        char *byte = new char[1 * 1024 * 1024];
        if (postion + 1 * 1024 * 1024 < length)
        {

            qint64 result = file.read(byte, 1 * 1024 * 1024);
            qDebug() << "uploadFile read=" << result;

            QByteArray arrByte(byte, 1 * 1024 * 1024);
            arrByte.size();

            request.setHeader(QNetworkRequest::LocationHeader, postion);
            reply = accessManager->post(request, arrByte);

            postion += 1 * 1024 * 1024;
        }
        else
        {
            const int left = length - postion;
            qint64 result = file.read(byte, left);
            qDebug() << result;

            QByteArray arrByte(byte, left);
            arrByte.size();

            request.setHeader(QNetworkRequest::LocationHeader, postion);
            reply = accessManager->post(request, arrByte);

            postion += left;
        }

        delete[]byte;

        QEventLoop loop;
        //QTimer::singleShot(40000, &loop, SLOT(quit()));
        connect(accessManager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));
        loop.exec();

        if (reply->error() == QNetworkReply::NoError)
        {
            QByteArray jpegData = reply->readAll();

            reply->deleteLater();

            QJsonParseError parse_error;
            const QJsonDocument &parse_doc = QJsonDocument::fromJson(jpegData, &parse_error);
            if (parse_error.error == QJsonParseError::NoError)
            {
                const QJsonObject &object = parse_doc.object();
                int status = object.value(QStringLiteral("status")).toInt();
                QString msg = object.value(QStringLiteral("msg")).toString();

            }
            else {
                error = QStringLiteral("data not json[")+ jpegData;
            }
        }
        else
        {
            qDebug() << "uploadfile error " << reply->error() << reply->errorString();
            error = reply->errorString();
            reply->deleteLater();
            break;
        }
    }
    
    delete accessManager;
    return bl;
}

Third, the data is sent using the GET

transfer

QByteArray retData = "";
m_http->get(m_urlSendcode + QString("?phone=%1").arg(phoneCode), retData);
bool Http::get(QString url, QByteArray& ret)
{
    QNetworkAccessManager *manager = new QNetworkAccessManager;
    QNetworkReply *reply;
    QNetworkRequest u = QNetworkRequest(QUrl(url));
    //u.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-Form-urlencoded");
    
    reply = manager->get(u);
    
    QEventLoop loop; // 使用事件循环使得网络通讯同步进行
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    QTimer::singleShot(6000, &loop, SLOT(quit()));
    loop.exec(); // 进入事件循环, 直到reply的finished()信号发出, 这个语句才能 //退出
    
    if (reply->error())
    {
        ret = reply->errorString().toLatin1();
        delete manager;        
        return false;
    }
    
    if (reply->isFinished()) {
        ret = reply->readAll();
        delete manager;
        return  true;
    }
    else {
        delete manager;        
        return false;
    }
}
Published 87 original articles · won praise 46 · views 80000 +

Guess you like

Origin blog.csdn.net/LearnLHC/article/details/104364116