Winsock HTTP POST 上传文件

1. InitSock.h

#pragma once #include <WinSock2.h> #pragma comment(lib, "WS2_32.lib") #include <Windows.h> class CInitSock { public: CInitSock() { WORD wVersionRequested = MAKEWORD(2, 2); WSADATA wsaData; ::WSAStartup(wVersionRequested, &wsaData); } ~CInitSock() { ::WSACleanup(); } };

 

2. HTTP POST 上传

#include <string> #include "InitSock.h" CInitSock g_initSock; void load_lrc(char **buffer) { FILE *fp = fopen("8.lrc", "rb"); fseek(fp, 0, SEEK_END); long l_file_len = ftell(fp); rewind(fp); *buffer = new char[l_file_len + 1]; memset(*buffer, 0, l_file_len + 1); fread(*buffer, l_file_len, 1, fp); fclose(fp); } int upload(LPCSTR lpszServer) { char *lrc = NULL; load_lrc(&lrc); SOCKET sock = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sock == INVALID_SOCKET) return 0; SOCKADDR_IN server; server.sin_family = AF_INET; server.sin_port = htons(80); struct hostent *host_addr = gethostbyname(lpszServer); if (host_addr == NULL) return -1; server.sin_addr.s_addr = *((int *) *host_addr->h_addr_list); if (::connect(sock, (SOCKADDR *) &server, sizeof(SOCKADDR_IN)) == SOCKET_ERROR) { ::closesocket(sock); return 0; } printf("ip address = %s, port = %d/n",inet_ntoa(server.sin_addr), ntohs(server.sin_port)); std::string header(""); header += "POST /song/addlyric HTTP/1.1/r/n"; header += "User-Agent: Mozilla/4.0/r/n"; header += "Host: www.test.com/r/n"; header += "Pragma: no-cache/r/n"; header += "Accept: */*/r/n"; header += "Content-Type: multipart/form-data; boundary=----------------------------64b23e4066ed/r/n"; std::string content(""); content += "------------------------------64b23e4066ed/r/n"; content += "Content-Disposition: form-data; name='id'/r/n/r/n"; content += "3365863/r/n"; content += "------------------------------64b23e4066ed/r/n"; content += "Content-Disposition: form-data; name='you_decide'; filename='demo.lrc'/r/n"; content += "Content-Type: custom/r/n/r/n"; content += lrc; content += "/r/n------------------------------64b23e4066ed--/r/n"; char temp[64] = {0}; sprintf(temp, "Content-Length: %d/r/n/r/n", content.length()); header += temp; std::string str_http_request = header + content; send(sock, str_http_request.c_str(), str_http_request.length(), 0); char szBuffer[1024] = {0}; while (true) { int nRet = ::recv(sock, szBuffer, sizeof(szBuffer), 0); if (nRet == 0 || nRet == WSAECONNRESET) { printf("Connection Closed./n"); break; } else if (nRet == SOCKET_ERROR) { printf("socket error/n"); break; } else { printf("recv() returned %d bytes/n", nRet); printf("received: %s/n", szBuffer); break; } } ::closesocket(sock); delete [] lrc; } int _tmain(int argc, _TCHAR* argv[]) { upload("www.test.com"); return 0; }

你可能感兴趣的:(socket,upload,header,File,buffer,FP)