-
HTTP - MFCPlatform/소켓 2009. 2. 14. 18:40#include <afxinet.h>
CInternetSession
INTERNET_OPEN_TYPE_DIRECT
.SetOption()
INTERNET_OPTION_CONNECT_TIMEOUT
.GetHttpConnection() // CHttpConnection
.OpenURL()
.Close()
CInternetException
.GetErrorMessage(()
CHttpConnection
.Close()
.OpenRequest() // CHttpFileHTTP_VERB_POST
CHttpFile
.Close()
.AddRequestHeaders()
.GetLength()
주의: 파일 크기가 아니다.
.ReadString()
.Read()
//.ReadHuge()
요청한 크기보다 작을 수 있다. // ???.Seek()
로컬 PC의 캐시에 적용되기 때문에 큰 파일에는 사용하면 안될 것 같음 // ???.SendRequest()
.SendRequestEx()
.EndRequest()
.WriteString()
.QueryInfo()
AfxParseURL()
<!-- my_form.html -->
<form action="my_form_action.php" method="post">
<p>이름: <input type="text" name="name" /></p>
<p>연령: <input type="text" name="age" /></p>
<p><input type="submit" /></p>
</form>
<!-- my_form_action.php -->
<?php echo htmlspecialchars($_POST['name']); ?>씨 안녕하세요.
당신은 <?php echo (int)$_POST['age']; ?>세입니다.
BOOL Request(LPCTSTR lpHostAddr, LPCTSTR lpObj, CString strSendMsg, DWORD* dwOutMsg, CString& strReciveMessage)
{
CInternetSession Session("test");
CHttpConnection* pServer = NULL;
CHttpFile *pFile = NULL;
BOOL bResult = FALSE;
CString strURL(lpHostAddr);
CString strObject(lpObj);
CString strHeader = "Content-Type: application/x-www-form-urlencoded\r\n"
"User-Agent: Mozilla/4.0";
CString strBuffer = _T("");
int nReadSize = 0;
try {
pServer = Session.GetHttpConnection(strURL);
// pServer = Session.GetHttpConnection(strURL, 80);
if (NULL == pServer) goto DONE;
pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObject);
if (NULL == pFile) goto DONE;
if(!(pFile->SendRequest(strHeader,(LPVOID)strSendMsg.GetBuffer(strSendMsg.GetLength()),
strSendMsg.GetLength())))
{
strSendMsg.ReleaseBuffer();
goto DONE;
}
strSendMsg.ReleaseBuffer();
} catch(CInternetException *e) {
TCHAR szError[255];
e->GetErrorMessage(szError,255);
... szError ...
goto DONE;
}
nReadSize = (int)pFile->Read(strReciveMessage.GetBuffer(pFile->GetLength()), pFile->GetLength());
strReciveMessage.ReleaseBuffer();
if (nReadSize != strReciveMessage.GetLength()) {
TRACE("파일 읽기 오류\n");
goto DONE;
}
*dwOutMsg = strReciveMessage.GetLength();
bResult = TRUE;
DONE:
if (pFile) {
pFile->Close();
delete pFile;
pFile = NULL;
}
if (pServer) {
pServer->Close();
delete pServer;
pServer = NULL;
}
Session.Close();
return bResult;
}
CString strReciveMessage(_T(""));
DWORD dwOutMsg;
if (Request("localhost", "/my_form_action.php", "name=...&age=...", &dwOutMsg, strReciveMessage))
AfxMessageBox(strReciveMessage);
#include <afx.h>
#include <afxinet.h>
BOOL GetFile (CHAR *szUrl, CHAR *szFileName)
{
TCHAR sz[1024];
CInternetSession session (_T("MyTest agent"), 1,
INTERNET_OPEN_TYPE_DIRECT);
CStdioFile* pFile = NULL;
CHAR szHead[] = "Accept: */*\r\n\r\n";
DWORD nRead;
CFile myFile;
CFileException fileException;
if ( !myFile.Open (szFileName, CFile::modeCreate | CFile::modeReadWrite,
&fileException ) )
{
cerr << "Can't open file: " << szFileName
<< " error = " << fileException.m_cause <<"\n";
return FALSE;
}
try
{
pFile = session.OpenURL (szUrl, 1, INTERNET_FLAG_RELOAD
|INTERNET_FLAG_TRANSFER_BINARY,
szHead, -1L);
}
catch (CInternetException *pEx)
{
cerr <<"OpenUrl failed: "<< pEx-> m_dwError << endl;
return FALSE;
}
do
{
nRead = pFile->Read(sz, 1023);
if (nRead != 0)
myFile.Write (sz, nRead);
}
while (nRead != 0);
myFile.Close();
pFile->Close();
if (pFile != NULL)
delete pFile;
session.Close();
return TRUE;
}
======
pFile은 CHttpFile *pFile ;입니다..
=====
TCHAR szContentLength[32];
DWORD dwInfoSize = 32;
DWORD dwFileSize = 0;
if(pFile->QueryInfo(HTTP_QUERY_CONTENT_LENGTH, szContentLength, &dwInfoSize, NULL))
{
dwFileSize = (DWORD) _ttol(szContentLength);
}
CInternetSession session;
CInternetFile* file=NULL;
try //URL를 열고자 시도
{
CString strURL( pURL );
file=(CInternetFile *) session.OpenURL(strURL);
}
catch (CInternetException* pEx)//파일을 열지 못하면
{
file =NULL;
//AfxMessageBox(_T("인터넷 접근 에러발생"));
return FALSE;
}
const int cMax = 655360;
unsigned char pBuffer[ cMax ];
int nSize = 0;
if(file)//파일을 열었다면
{
//버퍼 설정
file->SetReadBufferSize(4096);
int nReceived = 0;
//파일을 읽는다.
nReceived = file->Read( pBuffer + nSize , cMax - nSize );
nSize = nReceived;
//파일 닫기
file->Close();
}
else
{
// 파일 받기 실패..
return FALSE;
}
// 지정한 웹사이트에 접속하여 원하는 Html 파일의 내용얻기
// StdAfx.h 파일에 CInternetSession 클래스를 사용하기 위해서 아래의 코드를 추가한다.
#include <afxinet.h>
// 지정한 웹사이트에 접속하여 원하는 Html 파일의 내용을 얻기위한 멤버함수
void 클래스명::OnOpenBtn()
{
// 세션 클래스 생성하기
// (선택) 일반적인 경우
CInternetSession session;
// (선택) 세션이 연결된 이후, 웹 사이트의 Html 정보가 변경된 사항을 가져올 경우
CInternetSession session(NULL, 1, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL,
INTERNET_FLAG_DONT_CACHE);
try {
// 세션 클래스를 이용하여 Html 파일 열기
// (선택) http://www.tipssoft.com/main.htm파일을 여는 일반적인 방법
CInternetFile *p_html = (CInternetFile *)session.OpenURL("http://www.tipssoft.com/main.htm");
// (선택) http://www.tipssoft.com/main.htm 파일의 내용이 중간에 변경되더라도 변경된 정보를 정확히
// 얻고 싶다면 아래와 같이 코드를 사용한다.
CInternetFile *p_html = (CInternetFile *)session.OpenURL(parm_url, 1,
INTERNET_FLAG_TRANSFER_ASCII | INTERNET_FLAG_DONT_CACHE);
if(p_html != NULL){
CString str, html_text;
// Html 정보를 가져올때 사용할 버퍼의 크기를 512Bytes로 설정한다.
p_html->SetReadBufferSize(512);
while(1){
// 더 이상 읽을 정보가 없다면 종료한다.
if(!p_html->ReadString(str)) break;
// 읽어 들인 정보는 html_text 문자열에 추가한다.
html_text += str;
}
// Html 파일을 닫는다.
p_html->Close();
// Html 파일 읽기에 사용한 객체를 파괴한다.
delete p_html;
// 세션을 닫는다.
session.Close();
// html_text 문자열에 http://www.tipssoft.com/main.htm 파일의 내용이 들어있다.
// html_text 문자열을 출력하는 코드를 추가한다.
}
} catch(CInternetException *){
// Html 정보 읽기를 시도하다 실패하면 아래의 코드가 수행된다.
MessageBox("서버에 접속할수 없습니다.", "접속 오류", MB_ICONSTOP);
}
}
// html, image를 가지고 오는 예제
#include <afxinet.h>
void CGetHtmlTestDlgDlg::OnButton1()
{
GetHtml("http://simple21.egloos.com", "test.htm");
GetImage("http://pds.egloos.com/logo/1/200504/20/80/c0010380.jpg", "test.jpg") ;
AfxMessageBox("done");
}
bool GetHtml(const char* strURL, const char* strSavePath)
{
CInternetSession session;
CInternetFile* pInternetFile = NULL;
try {
session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 1000);
session.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 3);
pInternetFile = (CInternetFile*) session.OpenURL(strURL);
} catch (CInternetException* m_pException) {
char szError[1024];
m_pException->GetErrorMessage(szError, 1024);
AfxMessageBox(szError);
pInternetFile = NULL;
m_pException->Delete();
return false;
}
if(pInternetFile == NULL) return false;
CString strLine, strHtml;
while(pInternetFile->ReadString(strLine) != NULL) {
strHtml += strLine;
strHtml += "
";
strLine.Empty();
}
FILE* fp = fopen(strSavePath, "w+t");
fprintf(fp, "%s", strHtml);
fclose(fp);
pInternetFile->Close();
delete pInternetFile; pInternetFile = NULL;
return true;
}
bool GetImage(const char* strURL, const char* strSavePath)
{
CInternetSession session;
CInternetFile* pInternetFile = NULL;
try {
session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 1000);
session.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 3);
pInternetFile = (CInternetFile*) session.OpenURL(strURL);
} catch (CInternetException* m_pException) {
char szError[1024];
m_pException->GetErrorMessage(szError, 1024);
AfxMessageBox(szError);
pInternetFile = NULL;
m_pException->Delete();
return false;
}
if(pInternetFile == NULL) return false;
unsigned char data[500];
int data_size = 0;
FILE* fp = fopen(strSavePath, "w+b");
while((data_size = pInternetFile->Read(data, 500)) != 0)
fwrite(data, sizeof(unsigned char), data_size, fp);
fclose(fp);
pInternetFile->Close();
delete pInternetFile; pInternetFile = NULL;
return true;
}
#include "stdafx.h"
#include "main.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
using namespace std;
void ParseCmdLine(int argc, TCHAR* argv[], TCHAR* envp[]);
void Say(CString status);
int TMainApp(int argc, TCHAR* argv[], TCHAR* envp[]) {
Say("Parsing command line...");
ParseCmdLine(argc, argv, envp);
Say("Allocating variables...");
CString m_sURL = "http://www.digital.go.kr/rss/fc_textxml.jsp?row=120&col=61®ion=7&locationcode=4111573000";
CInternetSession m_Session;
CHttpConnection* m_pHttpConnection=NULL;
CHttpFile* m_pHttpFile = NULL;
Say("Connecting...");
try {
m_pHttpConnection = m_Session.GetHttpConnection(m_sURL,(INTERNET_PORT)80, NULL, NULL);
if( m_pHttpConnection == NULL )
throw CString("Http connection failed");
m_pHttpFile = (CHttpFile*)m_Session.OpenURL(m_sURL);
if( !m_pHttpFile ) {
m_pHttpFile->Close();
delete m_pHttpFile;
throw CString("HttpFile connection failed");
}
}
catch ( CInternetException *pEx ) {
if ( m_pHttpFile) {
m_pHttpFile->Close();
delete m_pHttpFile;
}
if ( m_pHttpConnection ) {
m_pHttpConnection->Close();
delete m_pHttpConnection;
}
TCHAR lpszErrorMessage[255];
pEx->GetErrorMessage(lpszErrorMessage, 255);
pEx->Delete();
cout << lpszErrorMessage << endl;
return 1;
}
catch (CString e) {
cout << "Error : " << (LPCTSTR)e << endl;
cout << "Program aborted..." << endl;
return -1;
}
Say("Connection established.");
Say("Listing file...");
CString line;
while ( m_pHttpFile->ReadString(line) != NULL ) {
// line += "\r\n";
wcout << (LPCTSTR)line << endl;
}
Say("Listing complete");
Say("Shutdown process started");
Say("Deleting m_pHttpFile...");
if ( m_pHttpFile) {
m_pHttpFile->Close();
delete m_pHttpFile;
}
Say("Deleting m_pHttpConnection...");
if ( m_pHttpConnection ) {
m_pHttpConnection->Close();
delete m_pHttpConnection;
}
return 0;
}
void ParseCmdLine(int argc, TCHAR* argv[], TCHAR* envp[]) {
// if ( argc != 2 )
// throw CString(L"Usage : inet.exe ip_address");
}
void Say(CString status) {
cout << (LPCTSTR)status << endl;
}
#include <afxinet.h>
CInternetSession Session;
CInternetFile* p_File=NULL;
try{
p_File = (CInternetFile *)Session.OpenURL(요기다 URL적음대욤);
}
catch(CInternetException *p_Ex)
{
p_File = NULL;
p_Ex = NULL;
MessageBox(NULL,"Error!!","경고",MB_OK);
}
if(p_File != NULL)
{
CString data;
p_File->SetReadBufferSize(4096);
for(int i=0; ; i++)
{
if(p_File->ReadString(data))
{
data += "\r\n";
*XML_code += data;
}
else break;
}
}
else{
MessageBox(NULL,"error.","error",MB_OK);
}
#include <afxinet.h>
{
CInternetSession session;
CString totalData;
totalData = "";
CString www_addr="HTTP://www.naver.com";
CInternetFile* pFile = (CInternetFile*)session.OpenURL(www_addr);
if(pFile)
{
CString strData;
pFile->SetReadBufferSize(4096);
while(pFile->ReadString(strData))
{
totalData = totalData + strData + "\r\n";
}
pFile->Close();
}
}
//웹페이지 소스읽어오기
#include <afxinet.h>
CInternetSession::OpenURL
CStdioFile* OpenURL( LPCTSTR pstrURL,
DWORD dwContext = 1, //
DWORD dwFlags = INTERNET_FLAG_TRANSFER_ASCII,
LPCTSTR pstrHeaders = NULL,
DWORD dwHeadersLength = 0 );
dwFlags:
INTERNET_FLAG_RELOAD
INTERNET_FLAG_DONT_CACHE
INTERNET_FLAG_TRANSFER_ASCII
INTERNET_FLAG_TRANSFER_BINARY
CString getURLContext(LPCTSTR pstrURL)
{
char* headers="Accept:*/*\r\n"
"Accept-Language:zh-cn\r\n"
"User-Agent:VCTestClient\r\n";
CString m_strHTML;
try
{
CInternetSession sess;
CHttpFile* pF=(CHttpFile*)sess.OpenURL(pstrURL,1,INTERNET_FLAG_TRANSFER_ASCII||INTERNET_FLAG_RELOAD,headers,strlen(headers));
CString szData,szAllData;
while(pF->ReadString(szData))
{
szAllData+="\r\n";
szAllData+=szData;
}
pF->Close();
delete pF;
sess.Close();
m_strHTML=szAllData;
}
catch(CException *e)
{
AfxMessageBox("실패");
}
return m_strHTML;
}
//CHttpConnection, CHttpFile을 이용한 웹문서 가져오기
CHttpConnection* GetHttpConnection( LPCTSTR pstrServer, INTERNET_PORT nPort = INTERNET_INVALID_PORT_NUMBER, LPCTSTR pstrUserName = NULL, LPCTSTR pstrPassword = NULL );
//예제소스
#include "stdafx.h"
#include "Usb_Finder_Client_ver.1.h"
#include <afxinet.h>
#include <vector>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
using namespace std;
// The one and only application object
void Print(CString status) {
cout << (LPCTSTR)status << endl;
}
CWinApp theApp;
using namespace std;
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
vector<CString> data;
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
Print("Parsing command line...");
Print("Allocating variab;les...");
CString m_sURL = "http://myhome.bcpark.net/~gameboyz21/connect.php?id=gameboyz";
CInternetSession m_Session;
CHttpConnection* m_pHttpConnection=NULL;
CHttpFile* m_pHttpFile = NULL;
Print("Connecting...");
try {
m_pHttpConnection = m_Session.GetHttpConnection(m_sURL,(INTERNET_PORT)80, NULL, NULL);
if( m_pHttpConnection == NULL )
throw CString("Http connection failed");
m_pHttpFile = (CHttpFile*)m_Session.OpenURL(m_sURL);
if( !m_pHttpFile ) {
m_pHttpFile->Close();
delete m_pHttpFile;
throw CString("HttpFile connection failed");
}
}
catch ( CInternetException *pEx ) {
if ( m_pHttpFile) {
m_pHttpFile->Close();
delete m_pHttpFile;
}
if ( m_pHttpConnection ) {
m_pHttpConnection->Close();
delete m_pHttpConnection;
}
TCHAR lpszErrorMessage[255];
pEx->GetErrorMessage(lpszErrorMessage, 255);
pEx->Delete();
cout << lpszErrorMessage << endl;
return 1;
}
catch (CString e) {
cout << "Error : " << (LPCTSTR)e << endl;
cout << "Program aborted..." << endl;
return -1;
}
Print("Connection established.");
Print("Listing file...");
CString line;
while ( m_pHttpFile->ReadString(line) != NULL ) {
// line += "\r\n";
data.push_back(line);
wcout << (LPCTSTR)line << endl;
}
Print("Listing complete");
Print("Shutdown process started");
}
for(int i = 0 ; i < data.size() ; i++)
{
cout << data[i] << endl;
}
return nRetCode;
CString strHeaders =
_T("Content-Type: application/x-www-form-urlencoded");
// URL-encoded form variables -
// name = "John Doe", userid = "hithere", other = "P&Q"
CString strFormData = _T("name=John+Doe&userid=hithere&other=P%26Q");
CInternetSession session;
CHttpConnection* pConnection =
session.GetHttpConnection(_T("ServerNameHere"));
CHttpFile* pFile =
pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST,
_T("FormActionHere"));
BOOL result = pFile->SendRequest(strHeaders,
(LPVOID)(LPCTSTR)strFormData, strFormData.GetLength());
CString strURL = _T("http://1*2.1*6.10*.1*4/loginProc.ahn");
CString strServerName;
INTERNET_PORT nPort;
DWORD dwServiceType, dwRet;
CString strObject;
DWORD dwHttpRequestFlags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE;
CInternetSession Session;
CHttpConnection *pConnection = NULL;
CHttpFile* pFile = NULL;
CONST TCHAR *szAcceptType=__HTTP_ACCEPT_TYPE;
CString strArguments = _T("id=id&passwd=pass");
CString strReferer = _T("http://1*2.1*6.10*.1*4/ahnAdmin/login.html");
LPCTSTR szContentType = TEXT("Content-Type: application/x-www-form-urlencoded\r\n");
// 웹 주소 분리
AfxParseURL(strURL, dwServiceType, strServerName, strObject, nPort);
// HTTP 컨넥션 연결
try{
pConnection = Session.GetHttpConnection(strServerName, nPort);
if(pConnection == NULL)
{
m_Editbox = "Fail";
goto END;
}
pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST,
strObject, strReferer, 1, &szAcceptType,NULL,
INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_FORMS_SUBMIT);
if(pConnection == NULL)
{
m_Editbox = "Fail";
goto END;
}
pFile->AddRequestHeaders(__HTTP_ACCEPT, HTTP_ADDREQ_FLAG_REPLACE, _tcslen(__HTTP_ACCEPT));
dwRet = pFile->SendRequest(szContentType, // additional HTTP header
_tcslen(szContentType), // additional HTTP header length
(LPVOID)(LPCTSTR)strArguments, // additional data in HTTP Post or HTTP Put
_tcslen(strArguments));
pFile->Close();
strURL = "http://1*2.1*6.10*.1*4/ahnAdmin/login_ok.html";
AfxParseURL(strURL, dwServiceType, strServerName, strObject, nPort);
pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_GET,
strObject, strReferer);
pFile->SendRequest();
}catch (CInternetException* e){e->Delete();} //예외 무시
if (!dwRet) m_Editbox = "False";
else m_Editbox = "Success";
END:
UpdateData(false);
}
BOOL Get(CString boardname)
{
CString URL;
URL = "http://gall.dcinside.com/list.php?id="+boardname;
DWORD dwServiceType;
INTERNET_PORT nPort;
CString strServer, strObject, strData;
if(!AfxParseURL(URL, dwServiceType, strServer, strObject, nPort))
{
OutputDebugString("ERROR# URL Parsing\n");
return FALSE;
}
DWORD dwRet;
CString strHeader = "Content-Type: application/x-www-form-urlencoded\r\n";
CInternetSession session("My Session");
CHttpConnection* pServer = NULL;
CHttpFile* pFile = NULL;
try
{
pServer = session.GetHttpConnection(strServer, nPort);
pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObject, 0, 1, 0, 0, INTERNET_FLAG_TRANSFER_ASCII | INTERNET_FLAG_RELOAD);
pFile->SetReadBufferSize(4096);
pFile->AddRequestHeaders(strHeader);
pFile->SendRequest();
pFile->QueryInfoStatusCode(dwRet);
dwRet = HTTP_STATUS_OK;
if(dwRet == HTTP_STATUS_OK)
{
CString strBuf;
while(pFile->ReadString(strBuf))
UTF8toUnicode(strBuf);
}
else
{
OutputDebugString("ERROR# HTTP_STATUS\n");
}
delete pFile;
delete pServer;
}
catch(CInternetException* pEx)
{
TCHAR szCause[255];
CString strError;
pEx->GetErrorMessage(szCause, 255);
strError.Format("ERROR# Connect Failed[%d] :", pEx->m_dwError);
strError += szCause;
strError += _T("\n");
OutputDebugString(strError);
session.Close();
return FALSE;
}
session.Close();
return TRUE;
}
#include <afxinet.h>
CInternetSession internetSession;
CHttpConnection * httpConnection = internetSession.GetHttpConnection("op.co.kr", (INTERNET_PORT)80,NULL ,NULL);//op.co.kr은 저희 회사 주소고요..이렇게 주소를 적고
CHttpFile * httpFile = httpConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, "/~eorsm/up_test.php");
///~eorsm/up_test.php는 파일이 업로드 되면 실행할 페이지이고요...
httpFile->AddRequestHeaders("Accept: text/*\r\nContent-Type: multipart/form-data; boundary=---------------------------7d13a23b368\r\nUser-Agent: VCApp\r\n");
////////////////////////////////////////////////////////application/octet-stream
CString sFile = _T( str1[i]);//str[1]은 전송할 파일의 경로입니다.
CString sPrefix;
sPrefix.Format(_T("\r\n-----------------------------7d13a23b368\r\nContent-Disposition: form-data; name="upfile"; filename="%s"\r\nContent-Type: application/octet-stream\r\n\r\n"), sFile);///upfile은 서버에서 파일을 받아 줄 변수 입니다..
DWORD dwPrefix = sPrefix.GetLength();
CString sSuffix = _T("\r\n\r\n-----------------------------7d13a23b368--\r\n");
DWORD dwSuffix = sSuffix.GetLength();
CFile postFile;
postFile.Open( str1[i], CFile::modeReadorCFile::typeBinary);
postFile.SeekToEnd();
DWORD dwFileSize = postFile.GetPosition();
postFile.SeekToBegin();
DWORD dwPostDataLen = dwPrefix + dwFileSize + dwSuffix;
BYTE * szPostData, * pCurrentByte;
szPostData = pCurrentByte = new BYTE[dwPostDataLen];
memcpy((void *)szPostData, (const void *)(LPCTSTR)sPrefix, dwPrefix);
pCurrentByte += dwPrefix;
pCurrentByte += postFile.Read((void *)pCurrentByte, dwFileSize);
memcpy((void *)pCurrentByte, (const void *)(LPCTSTR)sSuffix, dwSuffix);
//////////////////////////////////////////////////////////
try
{
httpFile->SendRequest(NULL, 0, (LPVOID)szPostData, dwPostDataLen);//요게 핵심인데 서버에 파일을 올리는 작업을 하는 함수 입니다..
DWORD dwRet;
httpFile->QueryInfoStatusCode(dwRet);
TCHAR szResp[1024];
while (httpFile->ReadString(szResp, 1024))
TRACE("%s\n", szResp);
delete (LPVOID)szPostData;
}
catch (CInternetException& exc)
{
TRACE("Caught Exception (%d)\n", exc.m_dwError);
}
httpFile->Close();
delete httpFile;
delete httpConnection;
}
return 0;
1. #include <afxinet.h> /* 이것먼저 include해주자 */
2.
3. CInternetSession internetSession;
4. CHttpConnection* httpConnection;
5. CHttpFile* httpFile;
6.
7. /* 서버에 연결(211.204.123.21 : 서버주소) */
8. httpConnection = internetSession.GetHttpConnection("211.204.123.21",
9. (INTERNET_PORT)80,NULL ,NULL);
10.
11. /* /upload/upload.php : 업로드후 불러낼 파일(upload.php에 데이터를 넘겨준다) */
12. httpFile = httpConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST,
13. "/upload/upload.php");
14.
15. /* 헤더전송 */
16. httpFile->AddRequestHeaders("Accept: text/*\r\nContent-Type: multipart/form-data; boundary=---------------------------7d13a23b368\r\nUser-Agent: VCApp\r\n");
17.
18. /* 전송할 파일 경로 저장 */
19. CString sFile = _T("C:\\test.zip");
20.
21. ///////////////* Prefix 저장 *//////////////
22. CString sPrefix;
23.
24. /* upfile : 서버에서 사용할 변수명 */
25. sPrefix.Format(_T("\r\n-----------------------------7d13a23b368\r\nContent-Disposition: form-data; name=\"upfile\"; filename=\"%s\"\r\nContent-Type: application/octet-stream\r\n\r\n"), sFile);
26.
27. /* Prefix Size */
28. DWORD dwPrefix = sPrefix.GetLength();
29.
30. //////////////* Suffix 저장 *///////////////
31. CString sSuffix = _T("\r\n\r\n-----------------------------7d13a23b368--\r\n");
32.
33. /* Suffxi Size */
34. DWORD dwSuffix = sSuffix.GetLength();
35.
36. /* 전송할 파일 오픈 */
37. CFile postFile;
38. postFile.Open(sFile, CFile::modeRead|CFile::typeBinary)
39.
40. /* 전송할 파일의 데이터 사이즈 */
41. postFile.SeekToEnd(); /* 맨뒤로가서 */
42. DWORD dwFileSize = postFile.GetPosition(); /* 사이즈를 구하고 */
43. postFile.SeekToBegin(); /* 다시 맨 앞으로 */
44.
45. /* 전송할 데이터를 저장하는 곳이다 */
46. BYTE * szPostData, * pCurrentByte;
47.
48. /* 전송할 데이터의 총 길이를 구한다 */
49. DWORD dwPostDataLen = dwPrefix + dwFileSize + dwSuffix;
50.
51. /* 전송할만큼 크기를 지정해 준다 */
52. szPostData = pCurrentByte = new BYTE[dwPostDataLen];
53.
54. /* 먼저 Prefix를 저장 */
55. memcpy((void *)szPostData, (const void *)(LPCTSTR)sPrefix, dwPrefix);
56. pCurrentByte += dwPrefix;
57.
58. /* 전송할 FileData를 저장 */
59. pCurrentByte += postFile.Read((void *)pCurrentByte, dwFileSize);
60.
61. /* 마지막으로 Suffix를 저장 */
62. memcpy((void *)pCurrentByte, (const void *)(LPCTSTR)sSuffix, dwSuffix);
63.
64. try {
65. /* 요청할 데이터의 전체 크기 세팅 */
66. httpFile->SendRequestEx(dwPostDataLen);
67.
68. /* Prefix + FileData + Suffix 전송(한번에) */
69. httpFile->Write(&szPostData[0], dwPostDataLen);
70. Sleep(10);
71.
72. /* 전송 완료 */
73. httpFile->EndRequest();
74. DWORD dwRet;
75. httpFile->QueryInfoStatusCode(dwRet);
76. TCHAR szResp[1024];
77. while (httpFile->ReadString(szResp, 1024))
78. TRACE("%s\n", szResp);
79. delete (LPVOID)szPostData;
80. }
81. catch (CInternetException& exc) {
82. TRACE("Caught Exception (%d)\n", exc.m_dwError);
83. }
비동기 모니커
CAsyncMonikerFile
OnDataAvailable
참조 사이트:
http://lostsin.springnote.com/pages/292140
http://www.tipssoft.com/bulletin/board.php?bo_table=FAQ&wr_id=280&page=3
http://simple21.egloos.com/310792
http://june84.tistory.com/46
http://cafe.naver.com/javacircle.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=16330
http://qwert.tistory.com/entry/CHttpConnection-CHttpFile%EC%9D%84-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EC%9B%B9%EB%AC%B8%EC%84%9C-%EA%B0%80%EC%A0%B8%EC%98%A4%EA%B8%B0