本文整理汇总了C++中sendRequest函数的典型用法代码示例。如果您正苦于以下问题:C++ sendRequest函数的具体用法?C++ sendRequest怎么用?C++ sendRequest使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sendRequest函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。
示例1: sendRequest
void Pillow::HttpClient::device_connected()
{
sendRequest();
}
开发者ID:K0n24d,项目名称:pillow,代码行数:4,代码来源:HttpClient.cpp
示例2: sendRequest
void MNMClass::requestSong(uint8_t _song) {
sendRequest(MNM_SONG_REQUEST_ID, _song);
}
开发者ID:jmamma,项目名称:mididuino,代码行数:3,代码来源:MNM.cpp
示例3: http_request
// Send HTTP get and wait for response (SSL/SPP)
static int http_request(char *filename, char *proto, bool requestingFile, struct timeval *tvEnd){
char buf[BUFSIZZ];
int r;
int len;
long bytes_read = 0;
// Compute expected data size
fSize = atoi(filename);
if (fSize == 0 && filename[0] != '0'){
if (requestingFile){
fSize = calculate_file_size(filename);
}else{
fSize = strlen("HTTP/1.0 200 OK\r\n");
}
}
sizeCheck = fSize;
experiment_info->file_size = fSize;
// Request file (either by name or by size)
if (requestingFile){
sendRequest(filename);
}
// Now read the server's response, assuming that it's terminated by a close
while(1){
// SPP read
if (strcmp(proto, "spp") == 0){
/*
#ifdef DEBUG
printf("[DEBUG] SPP_read\n");
#endif
*/
SPP_SLICE *slice; // slice for SPP_read
SPP_CTX *ctx; // context pointer for SPP_read
r = SPP_read_record(ssl, buf, BUFSIZZ, &slice, &ctx);
#ifdef DEBUG
printf("[INFO] Read %d bytes\n", r);
#endif
if (ssl->read_stats.app_bytes == fSize){
printf("[INFO] Read %d bytes as expected (fSize=%d). Stopping timer\n", ssl->read_stats.app_bytes, fSize);
// Stop the timer here (avoid shutdown crap)
gettimeofday(tvEnd, NULL);
#ifdef VERBOSE
fwrite(buf, 1, len, stdout);
#endif
break;
//goto shutdown;
}
switch(SSL_get_error(ssl, r)){
case SSL_ERROR_NONE:
len = r;
break;
case SSL_ERROR_ZERO_RETURN:
goto shutdown;
case SSL_ERROR_SYSCALL:
fprintf(stderr, "SSL Error: Premature close\n");
goto done;
default:
berr_exit("SSL read problem");
}
}
// SSL read
else if (strcmp(proto, "ssl") == 0){
/*
#ifdef DEBUG
printf("[DEBUG] SSL_read\n");
#endif
*/
r = SSL_read(ssl, buf, BUFSIZZ);
#ifdef DEBUG
printf("[DEBUG] Read %d bytes\n", r);
#endif
if (ssl->read_stats.app_bytes == fSize){
printf("[INFO] Read %d bytes as expected (fSize=%d). Stopping timer\n", ssl->read_stats.app_bytes, fSize);
gettimeofday(tvEnd, NULL);
// Write buf to stdout
#ifdef VERBOSE
fwrite(buf, 1, len, stdout);
#endif
break;
}
switch(SSL_get_error(ssl, r)){
case SSL_ERROR_NONE:
len = r;
break;
case SSL_ERROR_ZERO_RETURN:
goto shutdown;
case SSL_ERROR_SYSCALL:
fprintf(stderr, "SSL Error: Premature close\n");
goto done;
default:
berr_exit("SSL read problem");
//.........这里部分代码省略.........
开发者ID:JudsonWilson,项目名称:mctls,代码行数:101,代码来源:wclient.c
示例4: sendRequest
void
LogFile::updateMonitor()
{
sendRequest(sensors().at(0)->hostName(),
QString("%1 %2" ).arg(sensors().at(0)->name()).arg(logFileID), 19);
}
开发者ID:aarontc,项目名称:kde-workspace,代码行数:6,代码来源:LogFile.cpp
示例5: fileInput
int Video::upload_data(
const uint64_t fileSize,
const string &sha,
const uint64_t sliceSize,
const string &sign,
const string &url,
const string &srcPath,
const uint64_t offset,
const string &session
) {
int ret = 0;
char tmp_buf[1024];
char buf[sliceSize];
vector<string> headers;
headers.push_back("Authorization: " + sign);
ifstream fileInput(srcPath.c_str(),
ios::in | ios::binary);
fileInput.seekg(offset);
uint64_t pos = offset;
while (fileSize > pos) {
reset();
uint64_t len =0;
fileInput.read(buf, sliceSize);
len = fileInput.gcount();
struct curl_httppost *firstitem = NULL,
*lastitem = NULL;
ret = curl_formadd(&firstitem, &lastitem,
CURLFORM_COPYNAME, "op",
CURLFORM_COPYCONTENTS, "upload_slice",
CURLFORM_END);
snprintf(tmp_buf, sizeof(tmp_buf),
"%lu", pos);
ret = curl_formadd(&firstitem, &lastitem,
CURLFORM_COPYNAME, "offset",
CURLFORM_COPYCONTENTS, tmp_buf,
CURLFORM_END);
ret = curl_formadd(&firstitem, &lastitem,
CURLFORM_COPYNAME, "session",
CURLFORM_COPYCONTENTS, session.c_str(),
CURLFORM_END);
ret = curl_formadd(&firstitem, &lastitem,
CURLFORM_COPYNAME, "filecontent",
CURLFORM_BUFFER, "data",
CURLFORM_BUFFERPTR, buf,
CURLFORM_BUFFERLENGTH, len,
CURLFORM_END);
int retry_times = 0;
do {
sendRequest(
url, 1, &headers,
NULL, firstitem);
dump_res();
if (retCode == 0) {
break;
}
retry_times++;
} while(retry_times < MAX_RETRY_TIMES);
curl_formfree(firstitem);
if (retCode != 0) {
return retCode;
}
pos += sliceSize;
}
return retCode;
}
开发者ID:tencentyun,项目名称:mvs-cpp-sdk,代码行数:80,代码来源:Video.cpp
示例6: QString
void HelpBrowser::gotoHelpFor( const QString & symbol )
{
QString code = QString("HelpBrowser.openHelpFor(\"%1\")").arg(symbol);
sendRequest(code);
}
开发者ID:acamari,项目名称:supercollider,代码行数:5,代码来源:help_browser.cpp
示例7: hasExtension
void SMTPConnection::authenticateSASL()
{
if (!dynamicCast <security::sasl::SASLAuthenticator>(getAuthenticator()))
throw exceptions::authentication_error("No SASL authenticator available.");
// Obtain SASL mechanisms supported by server from ESMTP extensions
std::vector <string> saslMechs;
hasExtension("AUTH", &saslMechs);
if (saslMechs.empty())
throw exceptions::authentication_error("No SASL mechanism available.");
std::vector <shared_ptr <security::sasl::SASLMechanism> > mechList;
shared_ptr <security::sasl::SASLContext> saslContext =
make_shared <security::sasl::SASLContext>();
for (unsigned int i = 0 ; i < saslMechs.size() ; ++i)
{
try
{
mechList.push_back
(saslContext->createMechanism(saslMechs[i]));
}
catch (const exceptions::no_such_mechanism&)
{
// Ignore mechanism
}
}
if (mechList.empty())
throw exceptions::authentication_error("No SASL mechanism available.");
// Try to suggest a mechanism among all those supported
shared_ptr <security::sasl::SASLMechanism> suggestedMech =
saslContext->suggestMechanism(mechList);
if (!suggestedMech)
throw exceptions::authentication_error("Unable to suggest SASL mechanism.");
// Allow application to choose which mechanisms to use
mechList = dynamicCast <security::sasl::SASLAuthenticator>(getAuthenticator())->
getAcceptableMechanisms(mechList, suggestedMech);
if (mechList.empty())
throw exceptions::authentication_error("No SASL mechanism available.");
// Try each mechanism in the list in turn
for (unsigned int i = 0 ; i < mechList.size() ; ++i)
{
shared_ptr <security::sasl::SASLMechanism> mech = mechList[i];
shared_ptr <security::sasl::SASLSession> saslSession =
saslContext->createSession("smtp", getAuthenticator(), mech);
saslSession->init();
if (saslSession->getMechanism()->hasInitialResponse())
{
byte_t* initialResp = 0;
size_t initialRespLen = 0;
saslSession->evaluateChallenge(NULL, 0, &initialResp, &initialRespLen);
string encodedInitialResp(saslContext->encodeB64(initialResp, initialRespLen));
delete [] initialResp;
if (encodedInitialResp.empty())
sendRequest(SMTPCommand::AUTH(mech->getName(), "="));
else
sendRequest(SMTPCommand::AUTH(mech->getName(), encodedInitialResp));
}
else
{
sendRequest(SMTPCommand::AUTH(mech->getName()));
}
for (bool cont = true ; cont ; )
{
shared_ptr <SMTPResponse> response = readResponse();
switch (response->getCode())
{
case 235:
{
m_socket = saslSession->getSecuredSocket(m_socket);
return;
}
case 334:
{
byte_t* challenge = nullptr;
size_t challengeLen = 0;
byte_t* resp = nullptr;
size_t respLen = 0;
try
{
// Extract challenge
saslContext->decodeB64(response->getText(), &challenge, &challengeLen);
//.........这里部分代码省略.........
开发者ID:ctpo6,项目名称:libvmime-rambler,代码行数:101,代码来源:SMTPConnection.cpp
示例8: lineEdit
lineEdit()->setStyleSheet(QLatin1String("QLineEdit {background:transparent;}"));
lineEdit()->installEventFilter(this);
ToolBarWidget *toolBar = qobject_cast<ToolBarWidget*>(parent);
if (toolBar && toolBar->getIdentifier() != ToolBarsManager::NavigationBar)
{
connect(toolBar, SIGNAL(windowChanged(Window*)), this, SLOT(setWindow(Window*)));
}
connect(SearchesManager::getInstance(), SIGNAL(searchEnginesModified()), this, SLOT(storeCurrentSearchEngine()));
connect(SearchesManager::getInstance(), SIGNAL(searchEnginesModelModified()), this, SLOT(restoreCurrentSearchEngine()));
connect(SettingsManager::getInstance(), SIGNAL(valueChanged(QString,QVariant)), this, SLOT(optionChanged(QString,QVariant)));
connect(this, SIGNAL(currentIndexChanged(int)), this, SLOT(currentIndexChanged(int)));
connect(lineEdit(), SIGNAL(textChanged(QString)), this, SLOT(queryChanged(QString)));
connect(m_completer, SIGNAL(activated(QString)), this, SLOT(sendRequest(QString)));
setWindow(window);
}
void SearchWidget::changeEvent(QEvent *event)
{
QComboBox::changeEvent(event);
if (event->type() == QEvent::LanguageChange && itemData(currentIndex(), Qt::AccessibleDescriptionRole).toString().isEmpty())
{
lineEdit()->setPlaceholderText(tr("Search using %1").arg(currentData(Qt::UserRole).toString()));
}
}
void SearchWidget::paintEvent(QPaintEvent *event)
开发者ID:DoctorJellyface,项目名称:otter-browser,代码行数:31,代码来源:SearchWidget.cpp
示例9: dc15network
Bool TERMWINDOWMEMBER dc15network(Bool master)
{
char line[100], line2[100];
label here, there;
FILE *file;
int i, rms;
Bool done = FALSE;
netFailed = FALSE;
const protocols *theProt = GetProtocolByKey(node->GetProtocol(), TRUE);
if (!theProt)
{
doccr();
cPrintf(getnetmsg(177));
doCR();
return (FALSE);
}
if (!CommPort->HaveConnection())
{
return (FALSE);
}
sprintf(line, sbs, LocalTempPath, mesgTmp);
unlink(line);
sprintf(line, getnetmsg(123), LocalTempPath);
unlink(line);
sprintf(line, getnetmsg(124), LocalTempPath);
unlink(line);
sprintf(line, getnetmsg(125), LocalTempPath);
unlink(line);
if ((file = fopen(line, FO_AB)) == NULL)
{
perror(getnetmsg(25));
return (FALSE);
}
for (i = get_first_room(here, there), rms = 0; i; i = get_next_room(here, there), rms++)
{
PutStr(file, there);
}
PutStr(file, ns);
fclose(file);
if (master)
{
sendRequest(theProt);
if (!CommPort->HaveConnection())
{
return (FALSE);
}
reciveRequest(theProt);
}
else
{
reciveRequest(theProt);
if (!CommPort->HaveConnection())
{
return (FALSE);
}
sendRequest(theProt);
}
if (!CommPort->HaveConnection() || netFailed)
{
return (FALSE);
}
if (master)
{
// clear the buffer
while (CommPort->HaveConnection() && CommPort->IsInputReady())
{
CommPort->Input();
}
}
makeSendFile();
if (!CommPort->HaveConnection() || netFailed)
{
return (FALSE);
}
// wait for them to get their shit together
cPrintf(getnetmsg(11));
CommPort->Output('X');
time_t t2 = 0;
const time_t t = time(NULL);
//.........这里部分代码省略.........
开发者ID:dylancarlson,项目名称:citplus,代码行数:101,代码来源:netdc15.cpp
示例10: client_task_impl
/**
* Handle client communications
*/
void client_task_impl() {
uip_tcp_appstate_t *app = &(uip_conn->appstate);
GETrequest *req = (GETrequest*)app->request;
if (uip_connected()) {
if (verbose) {
Serial.print("Connected to ");
Serial.println(req->hostName);
}
app->ackedCount = 0;
sendRequest();
}
// Did we get an ack for the last packet?
if (uip_acked()) {
// Record the bytes that were successfully sent
app->ackedCount += app->sentCount;
app->sentCount = 0;
// Check if we're done or need to send more content for this
// request
if (app->ackedCount != (int)app->cursor) {
// Generate the post again to send the next packet of data
sendRequest();
}
}
if (uip_rexmit()) {
sendRequest();
}
if (uip_newdata()) {
setRXPin(HIGH);
if (verbose) {
Serial.print("RX ");
Serial.print(uip_datalen());
Serial.print(" bytes from ");
Serial.println(req->hostName);
}
// Check if the sketch cares about the returned data
if ((req->returnFunc) && (uip_datalen() > 0)){
// Call the sketch's callback function
req->returnFunc((char*)uip_appdata, uip_datalen());
}
}
if (uip_aborted() || uip_timedout() || uip_closed()) {
if (req != NULL) {
if (verbose) {
Serial.print("Ended connection with ");
Serial.println(req->hostName);
}
if (req->returnFunc) {
// Call the sketch's callback function with 0 bytes to indicate End Of Data
req->returnFunc((char*)uip_appdata, 0);
}
// Remove the request from the connection
app->request = NULL;
// Request is no longer active
req->active = false;
}
}
}
开发者ID:cameronr,项目名称:WiShield_user_contrib,代码行数:71,代码来源:WiServer.cpp
示例11: qDebug
void YahooFinanceNetworkRequest::handleReply(QNetworkReply *pReply)
{
if (!pReply)
{
qDebug() << "YahooFinanceNetworkRequest::handleReply, null handle, ignored";
return;
}
if (pReply == mpNetworkReply.data())
{
qDebug() << "YahooFinanceNetworkRequest::handleReply, reply belongs to us, parsing data...";
const QVariant http_status_code = pReply->attribute(
QNetworkRequest::HttpStatusCodeAttribute);
bool is_error = pReply->error() != QNetworkReply::NoError;
qDebug() << "YahooFinanceNetworkRequest::handleReply, HTTP status:"
<< http_status_code.toString()
<< ", is error:" << is_error;
if (!is_error && HTTP_REPLY_CODE_OK == http_status_code.toInt())
{
int line_index = 0;
while (pReply->canReadLine() && mTickers.count() > line_index)
{
const QString line(pReply->readLine());
const QString ticker = mTickers.at(line_index);
const QStringList data = line.simplified().split(",");
if (mParameters.count() == data.count())
{
QMap<YahooFinance::StockParameter, QString> data_mappings;
for (int value_index = 0; value_index < data.count(); value_index++)
{
const YahooFinance::StockParameter param = mParameters.at(value_index);
const QString value = data.at(value_index);
qDebug() << "ticker:" << ticker << ", param:" << param << ", value:" << value;
data_mappings.insert(param, value);
}
emit parametersReceived(mQueryIdentifier, ticker, data_mappings);
}
else
{
handleError();
}
line_index++;
}
}
else if (HTTP_REPLY_MOVED_PERMANENTLY == http_status_code)
{
const QVariant redirection_url = pReply->attribute(
QNetworkRequest::RedirectionTargetAttribute);
qDebug() << "Moved permanently, url:" << redirection_url;
mUrl.setUrl(redirection_url.toString());
sendRequest();
}
else
{
handleError();
qDebug() << "YahooFinanceNetworkRequest::handleReply, ERROR";
}
mpNetworkReply.reset();
}
else
{
qDebug() << "YahooFinanceNetworkRequest::handleReply, unknown handle, not handled";
pReply->deleteLater();
}
}
开发者ID:juhapsav,项目名称:YahooFinanceQt,代码行数:68,代码来源:yahoofinancenetworkrequest.cpp
示例12: sizeof
//.........这里部分代码省略.........
// allocate enough for a base64-encoded digest
size_t authSize = proxyUser.size() +
proxyPassword.size() + 1;
// 11 extra bytes for prefix and terminator
char * digest = (char *) malloc(authSize * 4 / 3 + 11);
strcpy(digest, "Basic ");
encode_base64((proxyUser + ":" + proxyPassword).c_str(),
authSize, (digest + 6));
Log::log(logModule, Log::LOG_MAX_DEBUG,
"BaseService::doRequest(): Using proxy auth as: %s",
proxyUser.c_str());
hostHeader = Http::Cookie("Proxy-Authorization", digest);
proxyHeaderList.push_back(hostHeader);
free(digest);
}
}
#endif
#endif
// retry to connect to server before marking it as down.
// making the number of attempts configurable may have a negative
// side effect on performance, if the the value is a high number.
int retryAttempts = 3;
int retryCount = 0;
while (retryCount < retryAttempts) {
retryCount++;
try {
const char *operation = "sending to";
Connection conn(svrInfo.getHost().c_str(), svrInfo.getPort(), svrInfo.useSSL());
#ifdef AGENT_PROXY_SUPPORT
std::string requestString = svrInfo.getURI().c_str();
/*
* In case the following request would go to a proxy
* we need to use full URL and special headers.
*/
if (useProxy && !(iter->useSSL())) {
requestString = iter->getURL();
headerList = proxyHeaderList;
}
#endif
status = sendRequest(conn, headerPrefix, svrInfo.getURI(),
uriParameters, headerList, cookieList,
dataLen > 0 ? contentLineChunk : emptyContentLine, headerSuffix,
bodyChunkList);
if (AM_SUCCESS == status) {
operation = "receiving from";
status = response.readAndParse(logModule, conn);
if (AM_SUCCESS == status) {
Log::log(logModule, Log::LOG_MAX_DEBUG, "Response::readAndParse() (%d) %s",
response.getBodyLen(), response.getBodyPtr() ? response.getBodyPtr() : "(NULL)");
}
}
if (AM_NSPR_ERROR == status) {
Log::log(logModule, Log::LOG_ALWAYS,
"BaseService::doRequest() NSPR failure while "
"%s %s", operation,
svrInfo.getURL().c_str());
}
if (AM_SUCCESS == status) {
break;
} else {
if (retryCount < retryAttempts) {
continue;
} else {
Log::log(logModule, Log::LOG_DEBUG,
"BaseService::doRequest() Invoking markSeverDown");
/*svrInfo.markServerDown(poll_primary_server);*/
}
}
} catch (const NSPRException& exc) {
Log::log(logModule, Log::LOG_ERROR,
"BaseService::doRequest() caught %s: %s called by %s", exc.what(), exc.getNsprMethod(),
exc.getThrowingMethod());
if (retryCount < retryAttempts) {
status = AM_NSPR_ERROR;
continue;
} else {
Log::log(logModule, Log::LOG_ERROR,
"BaseService::doRequest() Invoking markSeverDown");
/*svrInfo.markServerDown(poll_primary_server);*/
status = AM_NSPR_ERROR;
}
}
} //end of while
if (AM_SUCCESS == status) {
break;
}
} // end of for
} else {
status = AM_BUFFER_TOO_SMALL;
}
return status;
}
开发者ID:JonathanFu,项目名称:OpenAM-1,代码行数:101,代码来源:base_service.cpp
示例13: main
int main(int argc, char * argv[]) {
//check comand line paremeters
if (argc < 10) {
printf("usage: client ip port requestfilename requestNum cancelOrStop(1 is cancel, 0 is stop) netinterface filterExpression serverbandstatus sleepTime\n");
return 1;
}
// check cancel parameter
int isCancel = 0;
char *prefix = argv[8];
int sleepTime = atoi(argv[9]);
if (strcmp(argv[5], "1") == 0) {
isCancel = 1;
}
//init logFile
char logFile[FILE_NAME_SIZE] = {0};
if (initLogFile(logFile, sizeof logFile -1, isCancel, prefix) != 0) {
fprintf(stderr, "init logfile failed\n");
return 1;
}
printf("isCancel:%d\n", isCancel);
printf("log file name is %s\n", logFile);
struct ClientSockInfo sockInfo;
if (initClientSockInfo(&sockInfo, argv[1], argv[2]) == 0) {
printf("init client sockinfo successfully\n");
} else {
fprintf(stderr, "init client sockinfo failed\n");
return 1;
}
char * requestFileName = argv[3];
int requestNum = atoi(argv[4]);
//init sniffPanel
struct SniffPanel sniffPanel;
sniffPanel.device = argv[6];
sniffPanel.filterExpression = argv[7];
sniffPanel.liveReadTimeOut = 2000;//default 2000 ms
sniffPanel.payloadFilePath = NULL;
sniffPanel.payloadFile = NULL;
sniffPanel.cbAfterSniff = &cbAfterSniff;
sniffPanel.cbWhenError = &cbForSniffError;
sniffPanel.cbLog = &cbForSniffLog;
sniffPanel.afterSniffArgs = (void *)logFile;
sniffPanel.errorArgs = NULL;
sniffPanel.isStopped = 1;
if (initSniff(&sniffPanel) != 0) {
fprintf(stderr, "init packet sniff error\n");
return 1;
} else {
printf("finish initializing packet sniff\n");
}
pthread_t sniffThread;
int i = 0;
while (i < requestNum) {
if (!sniffPanel.isStopped) {
printf("we need to stop the last sniff before starting new round\n");
if (stopSniff(&sniffPanel) != 0) {
fprintf(stderr, "stop sniff failed\n");
continue;
} else {
printf("finish stopping the last sniff before starting new round\n");
}
}
i++;
printf("round %d\n", i);
//create connection to server
//if (i == 1 || !isCancel) {
// if (createNewConn(&sockInfo) != 0) {
// fprintf(stderr, "create new connection failed \n");
// return 1;
// } else {
// printf("connect to server %s:%d successfully from port %d\n", sockInfo.serverIpStr, sockInfo.serverPort, sockInfo.clientPort);
// }
//}
if (createNewConn(&sockInfo) != 0) {
i--;
fprintf(stderr, "create new connection failed \n");
continue;
} else {
printf("connect to server %s:%d successfully from port %d\n", sockInfo.serverIpStr, sockInfo.serverPort, sockInfo.clientPort);
}
//configure packet sniff and start thread
sniffPanel.packetNum = 0;
sniffPanel.payloadSize = 0;
sniffPanel.isStopped = 0;
pthread_create(&sniffThread, NULL, sniffThreadFunc, (void *)&sniffPanel);
printf("finish starting thread for sniff\n");
//send request
if (sendRequest(&sockInfo, requestFileName, strlen(requestFileName)) == 0) {
printf("send request successfully\n");
} else {
fprintf(stderr, "send request failed\n");
shutdown(sockInfo.clientSockFd, SHUT_RDWR);
i--;
continue;
}
//receive response within random time
int randomSecs = generateRandom(RANDOM_RANGE);
randomSecs += 10;
//.........这里部分代码省略.........
开发者ID:mixianghang,项目名称:newhttp2,代码行数:101,代码来源:client.c
示例14: reset
int Video::upload(
const string &srcPath,
const string &bucketName,
const string &dstPath,
const string &videoCover,
const string &bizAttr,
const string &title,
const string &desc,
const string &magicContext) {
reset();
int ret = 0;
ret = access(srcPath.c_str(), F_OK | R_OK);
if (ret != 0) {
retCode = VIDEO_FILE_NOT_EXISTS;
retMsg = "file not exist or can not be read...";
return retCode;
}
string encodePath = videoUrlEncode(dstPath);
uint64_t expired = time(NULL) + EXPIRED_SECONDS;
string url = generateResUrl(bucketName, encodePath);
string sign =
Auth::appSign(
APPID, SECRET_ID, SECRET_KEY,
expired, bucketName);
vector<string> headers;
headers.push_back("Authorization: " + sign);
string sha1 = genFileSHA1AndLen(srcPath);
struct curl_httppost *firstitem = NULL,
*lastitem = NULL;
ret = curl_formadd(&firstitem, &lastitem,
CURLFORM_COPYNAME, "op",
CURLFORM_COPYCONTENTS, "upload",
CURLFORM_END);
ret = curl_formadd(&firstitem, &lastitem,
CURLFORM_COPYNAME, "sha",
CURLFORM_COPYCONTENTS, sha1.c_str(),
CURLFORM_END);
ret = curl_formadd(&firstitem, &lastitem,
CURLFORM_COPYNAME, "video_cover",
CURLFORM_COPYCONTENTS, videoCover.c_str(),
CURLFORM_END);
ret = curl_formadd(&firstitem, &lastitem,
CURLFORM_COPYNAME, "biz_attr",
CURLFORM_COPYCONTENTS, bizAttr.c_str(),
CURLFORM_END);
ret = curl_formadd(&firstitem, &lastitem,
CURLFORM_COPYNAME, "video_title",
CURLFORM_COPYCONTENTS, title.c_str(),
CURLFORM_END);
ret = curl_formadd(&firstitem, &lastitem,
CURLFORM_COPYNAME, "video_desc",
CURLFORM_COPYCONTENTS, desc.c_str(),
CURLFORM_END);
ret = curl_formadd(&firstitem, &lastitem,
CURLFORM_COPYNAME, "magicContext",
CURLFORM_COPYCONTENTS, magicContext.c_str(),
CURLFORM_END);
ret = curl_formadd(&firstitem, &lastitem,
CURLFORM_COPYNAME, "filecontent",
CURLFORM_FILE, srcPath.c_str(),
CURLFORM_END);
sendRequest(url, 1, &headers, NULL, firstitem);
curl_formfree(firstitem);
return retCode;
}
开发者ID:tencentyun,项目名称:mvs-cpp-sdk,代码行数:80,代码来源:Video.cpp
示例15: qDebug
//.........这里部分代码省略.........
requestData.remove(0, pos + 2);
QList<QByteArray> entries = requestLine.split(' ');
QByteArray method = entries.value(0);
QByteArray address = entries.value(1);
QByteArray version = entries.value(2);
qDebug( ) << __FILE__ << __FUNCTION__ << "Processing " << address;
QUrl url = QUrl::fromEncoded(address);
if (!url.isValid()) {
//qWarning() << "Invalid URL:" << url;
socket->disconnectFromHost();
return;
}
//Act as server is request are for local server
if ((url.host() == "") && (QFile(address).exists())) {
//qDebug( ) << __FILE__ << __FUNCTION__ << "Sending " << address;
QByteArray header;
QTextStream headerStream(&header, QIODevice::WriteOnly);
//Construct response header
headerStream << "HTTP/1.0 200 OK" << endl;
headerStream << "Server: gpsbook/" << qApp->applicationVersion() << endl;
headerStream << "Date: " << QDateTime::currentDateTime().toUTC().toString("ddd, dd MMM yyyy hh:mm:ss") << "GMT" << endl;
headerStream << "Content-Type: text/html; charset=utf-8" << endl;
headerStream << "Connection: close" << endl;
headerStream << "Pragma: no-cache" << endl;
headerStream << "Cache-Control: no-cache" << endl;
QFile file(address);
if (!file.open(QFile::ReadOnly | QFile::Text))
{
qWarning() << "Cannot open:" << address;
socket->disconnectFromHost();
return ;
}
QByteArray content;
QTextStream contentStream(&content, QIODevice::WriteOnly);
while (!file.atEnd()) {
contentStream << file.readLine() << endl;
}
headerStream << "Content-Length:" << content.size() << endl;
headerStream << "" << endl;
socket->write(header);
socket->write(content);
//qDebug( ) << __FILE__ << __FUNCTION__ << "File sent (" << content.size() << "bytes) :-)";
socket->disconnectFromHost();
return;
}
#if ( QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) )
// Some finction of QUrl have been deprecated
// This code is require for the internet browser and should be reviewed.
#else
#ifdef Q_OS_LINUX
//Remove advert to speedup development ;-)
if (url.toString().contains("googlesyndication") ||
url.toString().contains("yieldmanager.com")) {
socket->disconnectFromHost();
return;
}
#endif
qDebug( ) << __FILE__ << __FUNCTION__ << "URL: " << url.toString();
QString host = url.host();
int port = (url.port() < 0) ? 80 : url.port();
QByteArray req = url.encodedPath();
if (url.hasQuery())
req.append('?').append(url.encodedQuery());
requestLine = method + " " + req + " " + version + "\r\n";
requestData.prepend(requestLine);
QString key = host + ':' + QString::number(port);
QTcpSocket *proxySocket = socket->findChild<QTcpSocket*>(key);
if (proxySocket) {
proxySocket->setObjectName(key);
proxySocket->setProperty("url", url);
proxySocket->setProperty("requestData", requestData);
proxySocket->write(requestData);
} else {
proxySocket = new QTcpSocket(socket);
proxySocket->setObjectName(key);
proxySocket->setProperty("url", url);
proxySocket->setProperty("requestData", requestData);
connect(proxySocket, SIGNAL(connected()), this, SLOT(sendRequest()));
connect(proxySocket, SIGNAL(readyRead()), this, SLOT(transferData()));
connect(proxySocket, SIGNAL(disconnected()), this, SLOT(closeConnection()));
connect(proxySocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(closeConnection()));
proxySocket->connectToHost(host, port);
}
#endif
} //WebProxy::processQuery
开发者ID:peder2key,项目名称:gpsbook,代码行数:101,代码来源:webproxy.cpp
示例16: sendRequest
/**
* send a GET request
* @return http code
*/
int HTTPClient::GET() {
return sendRequest("GET");
}
开发者ID:ettisan,项目名称:Arduino,代码行数:7,代码来源:ESP8266HTTPClient.cpp
示例17: code
void HelpBrowser::goHome()
{
static QString code( "HelpBrowser.goHome" );
sendRequest(code);
}
开发者ID:acamari,项目名称:supercollider,代码行数:5,代码来源:help_browser.cpp
示例18: sendRequest
void UpdateChecker::start() {
sendRequest();
}
开发者ID:2asoft,项目名称:tdesktop,代码行数:3,代码来源:autoupdater.cpp
示例19: qDebug
bool HttpAgent::async(const QObject * receiver, const char * method,
const QString& httpMethod, const Route& route, const QMap<QString, QVariant>& params,
const QMap<QString, QString>& filePaths,
const QMap<QString, QVariant>& argsToSlot,
const QObject * downloadProgressReceiver, const char * downloadProgressMethod
)
{
//在路由里取出url规则
QString routePattern = route.pattern();
qDebug() << "Services::async():" << routePattern;
//遍历所有"默认参数"(如:_format, _locale), 做替换
QMapIterator<QString, QVariant> defaultParamIterator(defaultParams);
while ( defaultParamIterator.hasNext() )
{
defaultParamIterator.next();
QString toReplace = QString("{") + defaultParamIterator.key() + QString("}");
routePattern.replace( toReplace, defaultParamIterator.value().toString() );
qDebug() << "Services::async():replace("<< defaultParamIterator.key() << "," << defaultParamIterator.value() << "):" << routePattern;
}
qDebug() << "Services::async():" << routePattern;
//QString paramsString;
QUrlQuery query;
int paramCount = 0;
QMapIterator<QString, QVariant> i(params);
while ( i.hasNext() )
{
i.next();
/*if ( paramCount > 0 )
{
paramsString += "&";
}
paramsString += i.key();
paramsString += '=';
paramsString += i.value();*/
QString value = QString( QUrl::toPercentEncoding( i.value().toString(), "", "+" ) );
query.addQueryItem(i.key(), value);
//replace if found in urlPattern
QString toReplace = QString("{") + i.key() + QString("}");
routePattern.replace( toReplace, i.value().toString() );
paramCount++;
}
/*QString paramString = query.query(QUrl::FullyEncoded);
QByteArray ba = QUrl::toPercentEncoding(paramString, "&=", "+");
qDebug() << "BA ==== " << ba;*/
qDebug() << "Services::async(): paramsString: \"" << query.query(QUrl::FullyEncoded) << "\""; //paramsString << "\"";
QString host = !route.host().isEmpty() ? route.host() : defaultHost;
QString url(defaultProtocol + "://" + host + routePattern);
//req.setRawHeader(QByteArray("X-Requested-With"), QByteArray("XMLHttpRequest"));
QMap<QString, QString> headers;
headers[ "X-Requested-With" ] = "XMLHttpRequest";
return sendRequest(httpMethod,
url,
params, //query.query(QUrl::FullyEncoded), //paramsString, //"email="+loginName+"&password="+password,
filePaths,
headers,
receiver, method, argsToSlot, downloadProgressReceiver, downloadProgressMethod );
}
开发者ID:hongtoushizi,项目名称:wpp-qt,代码行数:70,代码来源:HttpAgent.cpp
示例20: getId
void
ClientHandler::check_create_pipeline_call()
{
Json::Value request;
Json::Value response;
std::string pipeId;
std::string objId;
Json::Value params;
Json::Value constructorParams;
Json::Value operationParams;
request["jsonrpc"] = "2.0";
request["id"] = getId();
request["method"] = "create";
params["type"] = "MediaPipeline";
params["sessionId"] = "123456";
request["params"] = params;
request["sessionId"] = "sessionId";
response = sendRequest (request);
BOOST_CHECK (!response.isMember ("error") );
BOOST_CHECK (response.isMember ("result") );
BOOST_CHECK (response["result"].isObject() );
BOOST_CHECK (response["result"].isMember ("value") );
BOOST_CHECK (response["result"]["value"].isString() );
pipeId = response["result"]["value"].asString();
params["type"] = "WebRtcEndpoint";
constructorParams ["mediaPipeline"] = pipeId;
params["constructorParams"] = constructorParams;
params["sessionId"] = "123456";
request["id"] = getId();
request["params"] = params;
response = sendRequest (request);
BOOST_CHECK (!response.isMember ("error") );
BOOST_CHECK (response.isMember ("result") );
BOOST_CHECK (response["result"].isObject() );
BOOST_CHECK (response["result"].isMember ("value") );
BOOST_CHECK (response["result"]["value"].isString() );
objId = response["result"]["valu
|
请发表评论