前端使用QT,构建url,发送get和post方法,QT的post代码如下:
QNetworkAccessManager *m_pHttpMgr = new QNetworkAccessManager(this);
QNetworkRequest requestInfo;
QString url = "http://自己的url";
QUrl strUrl = url;
requestInfo.setUrl(strUrl);
requestInfo.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
requestInfo.setRawHeader("Content-Type", "charset='utf-8'");
QByteArray bodyData;
bodyData.append("name=john&");
bodyData.append("password=123456");
QNetworkReply *reply = m_pHttpMgr->post(requestInfo, bodyData);
QEventLoop eventLoop;
connect(m_pHttpMgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
eventLoop.exec();
if (reply->error() == QNetworkReply::NoError)
{
QByteArray responseByte = reply->readAll();
//成功
}
else
{
//失败
}
reply->deleteLater();
后台C# WEB-API代码如下:
string m_UserName = string.Empty;
string m_Password = string.Empty;
var request = HttpContext.Current.Request;
NameValueCollection nvCollection = request.Params;
if (nvCollection.GetValues("name") == null ||
nvCollection.GetValues("password") == null)
return false;
看着代码没什么问题,但是用request.Params始终获取不到数据。同事的另一段代码却可以成功,两段代码几乎一样。后来通过不断验证,发现问题所在:
requestInfo.setRawHeader("Content-Type", "charset='utf-8'");
requestInfo.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
charset='utf-8'的请求头若是先设置,后台的参数就可以获取到,若是后设置就获取不到。
注:
request.Params只可以获取到以x-www-form-urlencoded或form-data格式发送的数据,若是以json形式发送的数据获取不到