problem of sending data with POST method
, WinINET API
![]() |
Наши проекты:
Журнал · Discuz!ML · Wiki · DRKB · Помощь проекту |
|
| ПРАВИЛА | FAQ | Помощь | Поиск | Участники | Календарь | Избранное | RSS |
| [152.53.39.118] |
|
|
Правила раздела Visual C++ / MFC / WTL (далее Раздела)
FAQ Раздела
Обновления для FAQ Раздела
Поиск по Разделу
MSDN Library Online
problem of sending data with POST method
, WinINET API
|
|
|
|
|
I have Apache2 server and PHP4 installed on my local computer for educational purposes.
I have the index2.php in my http server directory which prints the myvar variables value. ![]() ![]() <?php echo '<html><head><title></title></head><body><p>'; echo $_POST["myvar"]; echo '</p></body></html>'; ?> This thing is working fine when I post data from the index2.htm file, ![]() ![]() <html><head><title>My PHP Query Page</title></head><body><br><br><center> <form action="index2.php" method="post"> <p> <input type="text" name="myvar"> <input type="submit" value="Submit Query"> <input type="reset" value=" Reset "> </p></form> </center> </body></html> but it doesn't work when I try to post some data using HttpOpenRequest(...), HttpSendRequest(...) WinINET APIs. ![]() ![]() #include <windows.h> #include <wininet.h> #include <iostream> using std::cout; void main() { HINTERNET hInternet = InternetOpen( "MyAgent", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL,0); cout<<"hInternet="<<(int)hInternet<<"\nGetLastError()="<<GetLastError()<<"\n\n"; HINTERNET hConnect = InternetConnect( hInternet, "127.0.0.1", 80, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); cout<<"hConnect="<<(int)hConnect<<"\nGetLastError()="<<GetLastError()<<"\n\n"; LPCTSTR AcceptTypes[] = { TEXT("*/*"), NULL}; HINTERNET hRequest = HttpOpenRequest( hConnect, "POST", "/index2.php", NULL, NULL, AcceptTypes, INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_RELOAD | INTERNET_FLAG_PRAGMA_NOCACHE, 0); cout<<"hRequest="<<(int)hRequest<<"\nGetLastError()="<<GetLastError()<<"\n\n"; char optData[] = "?myvar=31"; BOOL retRes = HttpSendRequest( hRequest, 0, 0, optData, lstrlen(optData) ); cout<<"retRes="<<(int)retRes<<"\nGetLastError()="<<GetLastError()<<"\n\n"; auto char buffer[4096]; auto DWORD uLong; if(InternetReadFile(hRequest,buffer,4096,&uLong) == FALSE){ MessageBox(0,"ERROR InternetReadFile returns NULL","ERROR",0); return; } for(UINT i=0;i<uLong;i++){ cout<<buffer[i]; } Sleep(20000); } The server respond like it doesn't receive any data. ![]() ![]() <html><head><title></title></head><body><p><br> <b>Warning</b>: Undefined index: myvar in <b>D:\!!HTTP!!\WWW\index2.php</b> on line <b>4</b><br> </p></body></html> I posted the optData string with the InternetSendRequest(...) optData[] = "?myvar=31"; is it right ? what I made wrong ? Regards, Aram |
|
Сообщ.
#2
,
|
|
|
|
Try delete from the variable optData symbol '?'
here try this, but it uses winsock2: ![]() ![]() #include <winsock2.h> #include <stdio.h> #pragma comment(lib, "ws2_32.lib") bool postSend( char* host, char* script, char* post ); int main( void ) { postSend("localhost","index2.php", "31"); return 0; } bool postSend( char* host, char* script, char* post ) { WSADATA wsaData; SOCKADDR_IN socketaddr; SOCKET sock; struct hostent *he; if (WSAStartup(MAKEWORD(2,2), &wsaData)) { printf ("Winsock not be initialized !\n"); WSACleanup(); return false; } sock = socket(AF_INET,SOCK_STREAM,0); socketaddr.sin_family = AF_INET; he = gethostbyname(host); socketaddr.sin_addr=*((struct in_addr *)he->h_addr); socketaddr.sin_port=htons(80); if(connect(sock,(sockaddr *)&socketaddr,sizeof(socketaddr))) { printf("Can\'t connect to %s\n\n",host); WSACleanup(); return false; } char request[1024]; char len[18]; strcpy(request,"POST http://"); strcat(request,host); strcat(request,"/"); strcat(request,script); strcat(request," HTTP/1.0\nAccept: text/html\nContent-Type: application/x-www-form-urlencoded\nContent-Length: "); strcat(request,_itoa(strlen(post)+strlen("myvar="),len,10)); strcat(request,"\n\nmyvar="); strcat(request,post); if(send(sock,request,strlen(request),0)<=0) { printf("Can\'t send request..."); WSACleanup(); return false; } char buffer[4096]=""; int nsize; while((nsize=recv(sock, buffer, sizeof(buffer), 0))!=SOCKET_ERROR) { buffer[nsize]=0; printf("%s",buffer); } } |
|
|
|
|
|
Thanks Jenizix.
Цитата Try delete from the variable optData symbol '?' it doesn't work. I decided to use sockets and I got some questions. What if I wanna pass more than one parameter ? ![]() ![]() POST http://localhost/index2.php HTTP/1.0 Accept: text/html Content-Type: application/x-www-form-urlencoded Content-Length: 8 myvar=31 how this request will look ? can you give me the POST methods request format for the HTTP 1.0 and HTTP 1.1 protocols ? |
|
Сообщ.
#4
,
|
|
|
|
I think I found out how to pass more than one parameter
Цитата POST http://localhost/index2.php HTTP/1.0 Accept: text/html Content-Type: application/x-www-form-urlencoded Content-Length: 18 myvar=14&myvar2=31 and also how I can send the request through some proxy server ? Thanks in advance. |
|
Сообщ.
#5
,
|
|
|
|
Try this code:
![]() ![]() #include <winsock2.h> #include <stdio.h> #pragma comment(lib, "ws2_32.lib") bool postSend( char* host, char* script, char* post); bool postSendProxy( char* host, char* script, char* post, char* proxy_host, int proxy_port); bool initSocket(); WSADATA wsaData; SOCKADDR_IN socketaddr; SOCKET sock; struct hostent *he; int main( void ) { printf("\n---------------------- Without use Proxy ----------------------\n"); postSend("jenizix.net.ru","script.php", "jenizix"); printf("\n\n---------------------- Use Proxy ----------------------\n"); postSendProxy("jenizix.net.ru","script.php", "jenizix","80.35.71.126",8080); scanf("A"); return 0; } bool initSocket() { if (WSAStartup(MAKEWORD(2,2), &wsaData)) { printf ("Winsock not be initialized !\n"); WSACleanup(); return false; } sock = socket(AF_INET,SOCK_STREAM,0); socketaddr.sin_family = AF_INET; return true; } bool postSend( char* host, char* script, char* post ) { initSocket(); he = gethostbyname(host); socketaddr.sin_addr=*((struct in_addr *)he->h_addr); socketaddr.sin_port=htons(80); if(connect(sock,(sockaddr *)&socketaddr,sizeof(socketaddr))) { printf("Can\'t connect to %s\n\n",host); WSACleanup(); return false; } char request[1024]; char len[18]; strcpy(request,"POST http://"); strcat(request,host); strcat(request,"/"); strcat(request,script); strcat(request," HTTP/1.0\nAccept: text/html\nContent-Type: application/x-www-form-urlencoded\nContent-Length: "); strcat(request,_itoa(strlen(post)+strlen("myvar="),len,10)); strcat(request,"\n\nmyvar="); strcat(request,post); if(send(sock,request,strlen(request),0)<=0) { printf("Can\'t send request..."); WSACleanup(); return false; } char buffer[4096]=""; int nsize; nsize=recv(sock, buffer, sizeof(buffer), 0); buffer[nsize]=0; printf("%s",buffer); buffer[0]='\0'; return true; } bool postSendProxy( char* host, char* script, char* post, char* proxy_host, int proxy_port) { initSocket(); socketaddr.sin_addr.s_addr=inet_addr(proxy_host); socketaddr.sin_port=htons(proxy_port); if(connect(sock,(sockaddr *)&socketaddr,sizeof(socketaddr))) { printf("Can\'t connect to proxy %s\n\n",host); WSACleanup(); return false; } char request[1024]; char len[18]; strcpy(request,"POST http://"); strcat(request,host); strcat(request,"/"); strcat(request,script); strcat(request," HTTP/1.0\nHost:"); strcat(request,host); strcat(request,"\nProxy Connection: Keep-Alive\n"); strcat(request,"Accept: text/html\nContent-Type: application/x-www-form-urlencoded\nContent-Length: "); strcat(request,_itoa(strlen(post)+strlen("myvar="),len,10)); strcat(request,"\n\nmyvar="); strcat(request,post); if(send(sock,request,strlen(request),0)<=0) { printf("Can\'t send request..."); WSACleanup(); return false; } char buffer[4096]=""; int nsize; while((nsize=recv(sock, buffer, sizeof(buffer), 0))!=SOCKET_ERROR) { buffer[nsize]=0; printf("%s",buffer); } buffer[0]='\0'; return true; } may be it code have bugs... from you plus for me =)))) А че по русски то нельзя поговорить =))) |
|
|
|
|
|
Спасибо
|
|
Сообщ.
#7
,
|
|
|
|
Not at all! =) Про плюсик еще один незабудь =)))))) Удачи!
|
|
Сообщ.
#8
,
|
|
|
|
Цитата А че по русски то нельзя поговорить =))) можно можно, просто copy-paste делать легче ![]() этот топик я создал в десятках международных форумах. в каждом узнавал что-то новое. Цитата Про плюсик еще один незабудь =)))))) что-то не получается, наверное надо ждать 24 часа после предыдущего плюсика. не беспокойтесь не забуду с HttpSendReuest(...) -ом тоже получилось, вот здесь написал --> my link Кстати какую документацию, книги можете предложить для изучения сетевых протоколов ? у меня Таненбаум - Компьютерные СЕТИ там о HTTP протоколах не так много написано. |