コード例 #1
0
ファイル: StdAfx.cpp プロジェクト: anzhsoft/Readings
//added by zhanganzhan on 20090317 to open a url on 20090317
BOOL UpLoad(LPCSTR URL)//, BOOL& quit, CSocketList& list, CMutex& mutex)
{
try{
	CHttpSocket HttpSocket;
	CFile DownloadFile;
	CString strServer,strObject;
	unsigned short nPort;
	DWORD dwServiceType;
	long nLength;
	const char *pRequestHeader = NULL;
	SOCKET tmpS = 0;
	if(!AfxParseURL(URL,dwServiceType,strServer,strObject,nPort))
		return FALSE;
	try{
		pRequestHeader = HttpSocket.FormatRequestHeader((LPTSTR)(LPCTSTR)strServer,(LPTSTR)(LPCTSTR)strObject,nLength, nPort);	
		if(!HttpSocket.Socket())
			throw 0;
		tmpS = HttpSocket.GetSocket();

		if(!HttpSocket.Connect((LPTSTR)(LPCTSTR)strServer,nPort))
			throw 1;
		if(!HttpSocket.SendRequest())
			throw 1;
		
		int nLineSize = 0;
		char szLine[256];
		while(nLineSize != -1)
			nLineSize = HttpSocket.GetResponseLine(szLine,256);
		
		HttpSocket.CloseSocket();
	}
	catch(int err){
// 		POSITION pos;
// 		CSingleLock SingleLock(&mutex);
		switch(err){
// 		case 3:
// 			DownloadFile.Close();
		case 2:
		case 1:
			HttpSocket.CloseSocket();
			break;
		}
		return FALSE;
	}
	return TRUE;

}
catch(...){
#ifdef _DEBUG
	AfxMessageBox("BOOL DownLoad(LPCSTR URL, LPCSTR Path, BOOL& quit, CSocketList& list)");
#endif
}
	return FALSE;
}
コード例 #2
0
void CTestHttpDlg::OnBnClickedBtnReq()
{
    UpdateData(); //control to value

    const char *pRequestHeader = NULL;
    DWORD dwServiceType = 0;
	AfxParseURL(m_strUrl, dwServiceType, m_strServer, m_strObject, m_port);
	
    BOOL IFOK = FALSE;
	long nLength = 0;

    CHttpSocket sock; 
	pRequestHeader = sock.FormatRequestHeaderSoap((LPTSTR)(LPCTSTR)m_strServer,(LPTSTR)(LPCTSTR)m_strObject,nLength);	
    
	m_editRequest.SetWindowText(pRequestHeader);
}
コード例 #3
0
bool CTestHttpDlg::WriteFile(CHttpSocket& rHttpSocket, int fileSize)
{
    int nCompletedSize = 0;

    //get log file name
	CString strFileName;	
    strFileName = c_strLog;

    CFile DownloadFile;
	DownloadFile.Open(strFileName,CFile::modeCreate | CFile::modeWrite);
	char pData[1024];
	int nReceSize = 0;
	DWORD dwStartTime,dwEndTime;

	while(nCompletedSize < fileSize)
	{
		dwStartTime = GetTickCount();
		nReceSize = rHttpSocket.Receive(pData,1024);
		if(nReceSize == 0)
		{
			AfxMessageBox("Server has been shut down..");
			break;
		}
		if(nReceSize == -1)
		{
			AfxMessageBox("receive timeout.");
			break;
		}
		dwEndTime = GetTickCount();
		DownloadFile.Write(pData,nReceSize);
		nCompletedSize += nReceSize;
		m_ctrlProgress.SetPos(nCompletedSize / 1024);
		
		//Speed
		CString strSpeed;
		//strSpeed.Format("%d",dwStartTime -dwEndTime);
		strSpeed.Format("%d",nReceSize);
		m_stcSpeed.SetWindowText(strSpeed);
	}
	DownloadFile.Close();
    return true;
}
コード例 #4
0
ファイル: file_down_load.hpp プロジェクト: njuicsgz/cpp
int DownLoadFile(std::string serverName, std::string URL,
        std::string localDirectory)
{
    FILE *fp;
    if (!(fp = fopen(localDirectory.c_str(), "wb+")))
    {
        printf("can't open local file\n");
        return -1;
    }

    CHttpSocket *cs = new CHttpSocket();
    cs->Socket();
    cs->Connect(serverName.c_str(), 80);

    long len = 0;
    std::string req = cs->FormatRequestHeader(serverName.c_str(), URL.c_str(),
            len, NULL, NULL, 0, 0, 0);
    cs->SendRequest(req.c_str(), len);

    int lens;
    std::string head = cs->GetResponseHeader(lens);

    printf("%s\n", head.c_str());

    int cnt = 0;
    int flag = head.find("Content-Length:", 0);
    int endFlag = head.find("\r\n", flag);
    std::string subStr = head.substr(flag, endFlag - flag);

    sscanf(subStr.c_str(), "Content-Length: %d", &lens);

    fseek(fp, 0, 0);

    while (cnt < lens)
    {
        char buff[1025];
        int tmplen = cs->Receive(buff, 1024);
        cnt += tmplen;
        fwrite(buff, 1, tmplen, fp);
    }

    fclose(fp);
    return 0;
}
コード例 #5
0
int CTestHttpDlg::ThreadFunc()
{
	//CFileDialog FileDlg(FALSE);
    
	CHttpSocket sock;
		
	
    BOOL IFOK = FALSE;

	IFOK = sock.Socket();    
    if(!IFOK)
    {
        ASSERT(FALSE);
        return 0;
    }

	sock.SetTimeout(10,0);
	IFOK = sock.Connect((LPTSTR)(LPCTSTR)m_strServer, m_port);
    if(!IFOK)
    {
        ASSERT(FALSE);
        return 0;
    }

    //set reqestheader
    string strsend = m_strRequest;      
    sock.SetRequest(strsend);
    
    //sock.SendRequest(strsend.c_str(), strsend.length() );
    sock.SendRequest( );

	int nLineSize = 0;

	char szLine[256+1];
    memset(szLine, 0, 256+1);

    m_ctrlList.ResetContent();
	while(nLineSize != -1)
	{
		nLineSize = sock.GetResponseLine(szLine,256);
		if(nLineSize > -1)
		{
			szLine[nLineSize] = '\0';
			m_ctrlList.AddString(szLine);
		}
	}
	//char szValue[30];
	//HttpSocket.GetField("Content-Length",szValue,30);
    
    string strContent = sock.GetContent();
    int pos = strContent.find("[");    
    string strJson = strContent.substr(pos + 1, strContent.length()-2 );
    int nFileSize = strContent.length();

    if(strJson.length() ){
        //JSONNode* node = (JSONNode*)json_parse(strJson.c_str() );
        //if(!node)
        //    return 0;
        //char jsontype = json_type(node);
        //if(JSON_NODE == jsontype)
        //{}
        //int nodesize = json_size(node);
        //json_char * res = json_as_string(json_at(node, 0));
    }
    //bool ifok = HttpSocket.GetContentLength(nFileSize);
	int nSvrState = sock.GetServerState();
	//int nFileSize = atoi(szValue);
	m_ctrlProgress.ShowWindow(SW_SHOW);
	m_ctrlProgress.SetRange(0,nFileSize / 1024);
	
	
    //bool ifwriteok = this->WriteFile(sock, nFileSize);
	
	m_ctrlProgress.ShowWindow(SW_HIDE);
	m_ctrlProgress.SetPos(0);

    string sdf;
    sdf.push_back('d');

    sock.CloseSocket();

	return 0;
}
コード例 #6
0
ファイル: WebAPI.cpp プロジェクト: 0vermind/NeoLoader
void CWebAPI::OnRequestCompleted()
{
	CHttpSocket* pRequest = (CHttpSocket*)sender();
	ASSERT(pRequest->GetState() == CHttpSocket::eHandling);
	QString Path = pRequest->GetPath();
	TArguments Cookies = GetArguments(pRequest->GetHeader("Cookie"));
	TArguments Arguments = GetArguments(pRequest->GetQuery().mid(1),'&');

	switch(pRequest->GetType())
	{
		case CHttpSocket::eDELETE:
			pRequest->RespondWithError(501);
		case CHttpSocket::eHEAD:
		case CHttpSocket::eOPTIONS:
			pRequest->SendResponse();
			return;
	}

	if(Path.compare("/WebAPI/") == 0)
		pRequest->RespondWithError(403);

	else if(Path.left(14).compare("/WebAPI/Icons/") == 0)
	{
		int Size;
		if(Arguments["Size"] == "Small")
			Size = 16;
		else // if(Arguments["Size"] == "Large")
			Size = 32;
		QString Ext = Split2(Path.mid(14), ".").first;
		QString IconPath = theCore->Cfg()->GetSettingsDir() + "/Cache/Icons/" + Ext + QString::number(Size) + ".png";
		if(!QFile::exists(IconPath))
		{
			if(theLoader)
				QMetaObject::invokeMethod(theLoader, "CreateFileIcon", Qt::BlockingQueuedConnection, Q_ARG(QString, Ext));
			else
				IconPath = ":/Icon" + QString::number(Size) + ".png";
		}
		pRequest->SetCaching(HR2S(48));
		pRequest->RespondWithFile(IconPath);
	}
	else if(Path.left(11).compare("/WebAPI/FS/") == 0)
	{
		StrPair CmdExt = Split2(Path.mid(11),".");

		QVariantMap Result;

		if(CmdExt.first.compare("dir", Qt::CaseInsensitive) == 0)
		{
			QVariantList Entrys;
			QString DirPath = Arguments["Path"];
			QDir Dir(DirPath);
			foreach (const QString& Name, Dir.entryList())
			{
				if (Name.compare(".") == 0 || Name.compare("..") == 0)
					continue;

				QVariantMap Entry;
				QFileInfo Info(DirPath + "/" + Name);
				Entry["Name"] = Info.fileName();
				Entry["Created"] = Info.created();
				Entry["Modifyed"] = Info.lastModified();
				if (Info.isDir())
					Entry["Size"] = "dir";
				else
					Entry["Size"] = Info.size();
				Entrys.append(Entry);
			}
			Result["List"] = Entrys;
		}
コード例 #7
0
ファイル: InfoPanel.cpp プロジェクト: acml/cvsnt
void CInfoPanel::LoaderThread()
{
	m_news.clear();
	CHttpSocket sock;
	cvs::string xml;
	CXmlTree tree;
	size_t len;

	if(!sock.create("http://march-hare.com"))
	{
		xml="<?xml version=\"1.0\" encoding=\"windows-1252\"?>\n<messages>\n<message><subject>Need assistance?  Click here for our professional support options!</subject><author>&quot;March Hare Support&quot; &lt;[email protected]&gt;</author><url>http://store.march-hare.com/s.nl?sc=2&amp;category=2</url></message>\n</messages>";
		len=xml.length();
	}
	else if(!sock.request("GET","/cvspro/prods-pre.asp?register=advert"))
	{
		xml="<?xml version=\"1.0\" encoding=\"windows-1252\"?>\n<messages>\n<message><subject>Need help NOW?  Click here for our professional support options!</subject><author>&quot;March Hare Support&quot; &lt;[email protected]&gt;</author><url>http://store.march-hare.com/s.nl?sc=2&amp;category=2</url></message>\n</messages>";
		len=xml.length();
	}
	if(sock.responseCode()!=200)
	{
		xml="<?xml version=\"1.0\" encoding=\"windows-1252\"?>\n<messages>\n<message><subject>Need help? Need integration?  Need training?  Click here for our professional support options!</subject><author>&quot;March Hare Support&quot; &lt;[email protected]&gt;</author><url>http://store.march-hare.com/s.nl?sc=2&amp;category=2</url></message>\n</messages>";
		len=xml.length();
	}
	else
	{
		cvs::string xml = sock.responseData(len);
	}
	if(!tree.ParseXmlFromMemory(xml.c_str()))
		return;
	CXmlNodePtr node = tree.GetRoot();
	if(strcmp(node->GetName(),"messages"))
		return;
	if(!node->GetChild("message"))
		return;

	do
	{
		news_t n;
		n.subject = node->GetNodeValue("subject");
		n.author = node->GetNodeValue("author");
		n.url = node->GetNodeValue("url");
		m_news.push_back(n);
	} while(node->GetSibling("message"));

	if(!m_hItemFont)
	{
		HFONT hFont = (HFONT)SendMessage(m_hListWnd,WM_GETFONT,0,0);
		if(!hFont) hFont=GetStockFont(DEFAULT_GUI_FONT);

		LOGFONT lf = {0};
		GetObject(hFont,sizeof(lf),&lf);
		lf.lfUnderline=true;
		m_hItemFont = CreateFontIndirect(&lf);
	}

	ListView_DeleteAllItems(m_hListWnd);
	ListView_DeleteColumn(m_hListWnd,1);
	LVCOLUMN lvc={0};
	lvc.mask=LVCF_WIDTH|LVCF_TEXT;
	lvc.cx=500;
	lvc.pszText=_T("Title");
	ListView_InsertColumn(m_hListWnd,0,&lvc);
	lvc.mask=LVCF_WIDTH|LVCF_TEXT;
	lvc.cx=300;
	lvc.pszText=_T("Author");
	ListView_InsertColumn(m_hListWnd,1,&lvc);

	for(size_t n=0; n<m_news.size(); n++)
	{
		LVITEM lvi = {0};
		cvs::wide wnews(m_news[n].subject.c_str());
		cvs::wide wauth(m_news[n].author.c_str());
		lvi.mask=LVIF_TEXT|LVIF_PARAM;
		lvi.iItem=(int)n;
		lvi.pszText=(LPWSTR)(const wchar_t*)wnews;
		lvi.lParam=(LPARAM)&m_news[n];
		int iItem = ListView_InsertItem(m_hListWnd,&lvi);
		ListView_SetItemText(m_hListWnd,iItem,1,(LPWSTR)(const wchar_t*)wauth);
	}
	m_bLoaded = true;
}
コード例 #8
0
ファイル: StdAfx.cpp プロジェクト: anzhsoft/Readings
BOOL DownLoad(LPCSTR URL, LPCSTR Path, BOOL& quit, CSocketList& list)
{
try{
	
	CHttpSocket HttpSocket;
	CFile DownloadFile;
	CString strServer,strObject;
	unsigned short nPort;
	DWORD dwServiceType;
	long nLength;
	const char *pRequestHeader = NULL;
	SOCKET tmpS = 0;
	if(!AfxParseURL(URL,dwServiceType,strServer,strObject,nPort)){
		//AfxMessageBox("AfxParseURL");
		return FALSE;
	}
	try{
		pRequestHeader = HttpSocket.FormatRequestHeader((LPTSTR)(LPCTSTR)strServer,(LPTSTR)(LPCTSTR)strObject,nLength, nPort);	
		if(!HttpSocket.Socket())
			throw 0;
		tmpS = HttpSocket.GetSocket();
		list.AddTail(tmpS);
		if(quit){
			//AfxMessageBox("quit");
			return FALSE;
		}
//		HttpSocket.SetTimeout(10000,0);
		if(!HttpSocket.Connect((LPTSTR)(LPCTSTR)strServer,nPort))
			throw 1;
		if(quit)
			return FALSE;
		if(!HttpSocket.SendRequest())
			throw 1;
		if(quit)
			return FALSE;
		int nLineSize = 0;
		char szLine[256];
		while(nLineSize != -1){
			nLineSize = HttpSocket.GetResponseLine(szLine,256);
			if(quit)
				return FALSE;
		}
		char szValue[30];
		BOOL bContLen = TRUE;
		int nFileSize = -1;
		if(HttpSocket.GetField("Content-Length",szValue,30)==-1)
			bContLen = FALSE;
		else
			nFileSize = atoi(szValue);
		if(quit)
			return FALSE;
//		int nSvrState = HttpSocket.GetServerState();
		int nCompletedSize = 0;
		if(!DownloadFile.Open(Path, CFile::modeCreate|CFile::modeWrite))
			throw 2;
		if(quit)
			return FALSE;
		char pData[1024];
		int nReceSize = 0;
		BOOL first = TRUE;
		while(!quit){
			nReceSize = HttpSocket.Receive(pData,1024);
			if(quit)
				return FALSE;
			if(nReceSize == 0)
				break;
			if(nReceSize == -1)
				throw 3;
			if(first&&!bContLen){
				char* temp = strstr(pData,"\n");
				if(!temp)
					throw 3;
				DownloadFile.Write(temp+2,nReceSize-(temp+2-pData));
			}
			else
				DownloadFile.Write(pData,nReceSize);
			nCompletedSize += nReceSize;
			first = FALSE;
			if(bContLen && nCompletedSize>=nFileSize)
				break;
		}
		if(!bContLen && !quit){
			long len = (long)DownloadFile.GetLength();
			DownloadFile.SetLength(len-7);
		}
		DownloadFile.Close();
		POSITION pos = list.Find(tmpS);
		if(pos)
			list.RemoveAt(pos);
		HttpSocket.CloseSocket();
	}
	catch(int err){
		POSITION pos;
		switch(err){
		case 3:
			DownloadFile.Close();
		case 2:
		case 1:
			pos = list.Find(tmpS);
			if(pos)
				list.RemoveAt(pos);
			HttpSocket.CloseSocket();
			break;
		}
		return FALSE;
	}
	return !quit;
}
catch(...){
#ifdef _DEBUG
//	AfxMessageBox("BOOL DownLoad(LPCSTR URL, LPCSTR Path, BOOL& quit, CSocketList& list)");
#endif
}
	return FALSE;
}