본문 바로가기
Programming/Tips(C++,C#)

vc++에서 HTTP Request(POST)전송하기

by 곰네Zip 2014. 2. 18.

참조 블로그 :  http://blog.naver.com/PostView.nhn?blogId=nawoo&logNo=80171143837

 

필요한 헤더 : wininet.h

 

URL_COMPONENT를 이용하여 InternetCrackUrl()을 이용해서 정보를 가져온 후 처리하자.

 

#include <wininet.h>

 

void func()

{

HINTERNET hSession = NULL, hConn = NULL, hReq = NULL;

char szurl[MAX_PATH];

char szAddHeader[1024];

 

memset( szurl, 0x00, sizeof(szurl));

memset( szAddHeader, 0x00, sizeof(szAddHeader));

 

sprintf( szurl, "myurl", params...);

wsprintf( szAddHeader, "Accept: text*/*\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 5.0;* Windows NT)\r\nContent-type: application/x-www-form-urlencoded\r\n\n\n");

//wchar로 지정해서 작업하여야할 것으로 보여짐. 우선은 대략적으로 작성하므로 skip!

//flag설정

DWORD dwFlags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_NO_COOKIES;

//urlcomponent 설정하고 internetcrackurl호출
 URL_COMPONENTS urlComp;

 memset(&urlComp, 0x00, sizeof(urlComp));

 char szScheme[INTERNET_MAX_SCHEME_LENGTH+1] = {0};
 char szHostName[INTERNET_MAX_HOST_NAME_LENGTH+1] = {0};
 char szUrlPath[INTERNET_MAX_PATH_LENGTH+1] = {0};
 char szUserName[INTERNET_MAX_USER_NAME_LENGTH+1] = {0};
 char szPassword[INTERNET_MAX_PASSWORD_LENGTH+1] = {0};
 char szExtraInfo[INTERNET_MAX_PATH_LENGTH+1] = {0};

 urlComp.dwStructSize = sizeof( URL_COMPONENTS);
 urlComp.lpszScheme = szScheme;
 urlComp.lpszHostName = szHostName;
 urlComp.lpszUrlPath = szUrlPath;
 urlComp.lpszUserName = szUserName;
 urlComp.lpszPassword = szPassword;
 urlComp.lpszExtraInfo = szExtraInfo;
 urlComp.dwSchemeLength = INTERNET_MAX_SCHEME_LENGTH;
 urlComp.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
 urlComp.dwUrlPathLength = INTERNET_MAX_PATH_LENGTH;
 urlComp.dwUserNameLength = INTERNET_MAX_USER_NAME_LENGTH;
 urlComp.dwPasswordLength = INTERNET_MAX_PASSWORD_LENGTH;
 urlComp.dwExtraInfoLength = INTERNET_MAX_PATH_LENGTH;

 

InternetCrackUrl( szurl, 0, 0, &urlComp);

 

hSession = InternetOpen("Request", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);

 if( hSession == NULL)
 {
  goto func_end;
 }

 hConnection = InternetConnectA(hSession, urlComp.lpszHostName, urlComp.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL);
 if( hConnection  == NULL)
 {
  goto func_end;
 }

 hReq = HttpOpenRequestA( hConn, "POST", urlComp.lpszUrlPath, "HTTP/1.1", NULL, NULL, dwFlags, 0); //여기서 Post가 아니면 "GET", default가 "GET"

 if( hRequest == NULL)
 {
  goto func_end;
 }

 dwFlags = HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD;
 if( HttpAddRequestHeaders( hReq , szAddHeader, strlen( szAddHeader), dwFlags) != TRUE)
 {
  goto func_end;
 }

 if( HttpSendRequest( hReq , NULL, NULL, szPostData, nLen) != TRUE)
 {
  goto func_end;
 }

 

func_end:

if( hSession != NULL){ InternetCloseHandle(hSession); }

if( hConn != NULL){ InternetCloseHandle(hConn ); }

if( hReq != NULL){ InternetCloseHandle(hReq ); }

}

반응형

댓글