Postman|Qt笔记-解决Could not get any response

Posted IT1995

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Postman|Qt笔记-解决Could not get any response相关的知识,希望对你有一定的参考价值。

这里Fiddler抓包是有显示的:

 但Postman却提示Could not get any response

 经过各种分析,发现问题出现在服务端

 

主要的原因就是Content-Length这个值,这里的已经告诉客户端是utf-8编码的,但里面含有中文,对应的数据Content-Length与body里面的长度不一致。

服务端是这样计算长度的:

class HttpResponse {

public:
    static QString success(const QString &body){

        QString ret = "HTTP/1.1 200 OK\\r\\n"\\
                      "Date: %1\\r\\n"\\
                      "Pragma: no-cache\\r\\n"\\
                      "Content-Type: application/json; charset=utf-8\\r\\n"\\
                      "Cache-Control: no-cache\\r\\n"\\
                      "Server: It1995HttpsWebServer\\r\\n"\\
                      "Content-Length: %2\\r\\n"\\
                      "\\r\\n"\\
                      "%3";

        QLocale locale = QLocale::English;
        QString format = "ddd,dd MM yyyy hh:mm:ss";
        QString currentTime =locale.toString(QDateTime::currentDateTime().toUTC(), format) + " GMT";

        int length = body.size();
        ret = ret.arg(currentTime).arg(length).arg(body);
        return ret;
    }
};

这种方式不正确,没有转换成utf-8计算长度,正确的代码:

class HttpResponse {

public:
    static QString success(const QString &body){

        QString ret = "HTTP/1.1 200 OK\\r\\n"\\
                      "Date: %1\\r\\n"\\
                      "Pragma: no-cache\\r\\n"\\
                      "Content-Type: application/json; charset=utf-8\\r\\n"\\
                      "Cache-Control: no-cache\\r\\n"\\
                      "Server: It1995HttpsWebServer\\r\\n"\\
                      "Content-Length: %2\\r\\n"\\
                      "\\r\\n"\\
                      "%3";

        QLocale locale = QLocale::English;
        QString format = "ddd,dd MM yyyy hh:mm:ss";
        QString currentTime =locale.toString(QDateTime::currentDateTime().toUTC(), format) + " GMT";

        int length = body.toUtf8().size();
        ret = ret.arg(currentTime).arg(length).arg(body);
        return ret;
    }
};

关键:

 

以上是关于Postman|Qt笔记-解决Could not get any response的主要内容,如果未能解决你的问题,请参考以下文章