C++ 如何使用 Qt 4.6.1 创建 HTTP POST 请求?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2214595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I create a HTTP POST request with Qt 4.6.1?
提问by Tobias Langner
How can I create a HTTP POST request with some URL encoded parameters using Qt 4.6.1?
如何使用 Qt 4.6.1 创建带有一些 URL 编码参数的 HTTP POST 请求?
I figured out that I can create a QNetworkRequest, set all the parameters there and send it via QNetworkAccessManagers post method. But how can I add some URL-encoded parameters to the request?
我发现我可以创建一个 QNetworkRequest,在那里设置所有参数并通过 QNetworkAccessManagers post 方法发送它。但是如何向请求添加一些 URL 编码的参数呢?
In the end I want to access the Eve APIusing Qt/C++. A Python example can be found here: http://www.eveonline.com/api/doc/example-python.asp
最后我想使用 Qt/C++访问Eve API。可以在此处找到 Python 示例:http: //www.eveonline.com/api/doc/example-python.asp
I managed it using something like (still to be refactored and formed into something useful):
我使用类似的东西来管理它(仍然需要重构并形成一些有用的东西):
QNetworkReply *requestApi(QNetworkAccessManager &nwam)
{
QNetworkRequest request(QUrl("http://api.eve-online.com/account/Characters.xml.aspx"));
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
QByteArray data;
QUrl params;
params.addQueryItem("userid","user");
params.addQueryItem("apiKey","key");
data.append(params.toString());
data.remove(0,1);
QNetworkReply *reply = nwam.post(request,data);
return reply;
}
回答by stach
Your solution is almost right. But one should use:
您的解决方案几乎是正确的。但是应该使用:
data = params.encodedQuery();
instead of
代替
data.append(params.toString());
data.remove(0,1);
to handle UTF8 strings properly.
正确处理 UTF8 字符串。
回答by Venemo
I'm sorry that I only find your post this late. However, I'll still try to help, in case anyone else is searching for the answer.
很抱歉这么晚才找到你的帖子。但是,我仍然会尽力提供帮助,以防其他人正在寻找答案。
By accident, I'm also working on an EVE API application, and I also tried the same way. Unfortunately, QNetworkManager
doesn't work that way, because it posts the request asynchronously. You have to connect a slot to its finished(QNetworkReply*)
signal.
偶然间,我也在开发一个 EVE API 应用程序,我也尝试过同样的方法。不幸的是,QNetworkManager
不能那样工作,因为它异步发布请求。您必须将插槽连接到其finished(QNetworkReply*)
信号。
I do it by making a request with a separate class called EveConnector
, processing the reply in the slot connected to the QNetworkManager
's finished
signal, and then calling back the requesting object through the connector class's own signals.
我通过使用名为 的单独类发出请求EveConnector
,处理连接到QNetworkManager
的finished
信号的插槽中的回复,然后通过连接器类自己的信号回调请求对象来实现。
I would happily share the code, if you ask.
如果你问,我很乐意分享代码。