关于Qt http的Post两种请求方式的编写方式,请求参数和请求体(json格式)

1.请求参数

void sendHttpRequest_param(QString url, QMap data){
	QUrl _url(url);
	QUrlQuery item;
	if (!data.isEmpty()) {
		QMap::iterator it;
		for (it = data.begin(); it != data.end(); ++it) {
			item.addQueryItem(it.key(), it.value());
		}
	}
	_url.setQuery(item);
	QNetworkAccessManager *accessManager = new QNetworkAccessManager(this);
	connect(accessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(finishedSlot(QNetworkReply*)));

	QNetworkRequest request;
	request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/x-www-form-urlencoded"));
	request.setUrl(_url);

	//设置SSL,HTTPS协议需要SSL证书
	QSslConfiguration m_sslConfig = QSslConfiguration::defaultConfiguration();
	m_sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);
	m_sslConfig.setProtocol(QSsl::TlsV1_2);
	request.setSslConfiguration(m_sslConfig);
	accessManager->get(request);
	return;
}
  1. 请求体
void sendHttpRequest(QString url, QByteArray data, QString type)
{
	QNetworkAccessManager *accessManager = new QNetworkAccessManager(this);
	connect(accessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(finishedSlot(QNetworkReply*)));

	QNetworkRequest request;
	request.setHeader(QNetworkRequest::ContentLengthHeader, data.length());
	request.setUrl(QUrl(url));

	if (type.toUpper() == "GET") {
		accessManager->get(request);
	}
	else if (type.toUpper() == "POST") {
		request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
		
		//设置SSL,HTTPS协议需要SSL证书
		QSslConfiguration m_sslConfig = QSslConfiguration::defaultConfiguration();
		m_sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);
		m_sslConfig.setProtocol(QSsl::TlsV1_2);
		request.setSslConfiguration(m_sslConfig);
		
		accessManager->post(request, data);
	}
	return;
}

你可能感兴趣的:(Qt)