| 43 | } |
| 44 | |
| 45 | Http::Response Http::post(const std::string& path, const std::string& data) |
| 46 | { |
| 47 | string request; |
| 48 | string response; |
| 49 | int resp_leng; |
| 50 | Response res; |
| 51 | res.status = -1; |
| 52 | |
| 53 | char buffer[1024] = {0}; |
| 54 | struct sockaddr_in serveraddr; |
| 55 | int sock; |
| 56 | |
| 57 | std::stringstream ss; |
| 58 | ss << data.length(); |
| 59 | |
| 60 | std::stringstream request2; |
| 61 | |
| 62 | request2 << "POST " << path << " HTTP/1.1"<<endl; |
| 63 | request2 << "User-Agent: RedisStudio" << endl; |
| 64 | //request2 << "" << endl; |
| 65 | request2 << "Host: " << _host << endl; |
| 66 | request2 << "Content-Length: " << data.length() << endl; |
| 67 | request2 << "Content-Type: application/json;charset=utf-8" << endl; |
| 68 | request2 << endl; |
| 69 | request2 << data; |
| 70 | request = request2.str(); |
| 71 | if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { |
| 72 | res.status = -1; |
| 73 | res.data = "open socket failed."; |
| 74 | return res; |
| 75 | } |
| 76 | memset(&serveraddr, 0, sizeof(serveraddr)); |
| 77 | serveraddr.sin_family = AF_INET; |
| 78 | serveraddr.sin_addr.s_addr = inet_addr(_ip.c_str()); |
| 79 | serveraddr.sin_port = htons((unsigned short) _port); |
| 80 | if (connect(sock, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0) { |
| 81 | res.status = -1; |
| 82 | res.data = "connect() failed"; |
| 83 | return res; |
| 84 | } |
| 85 | //send request |
| 86 | if (send(sock, request.c_str(), request.length(), 0) != request.length()) { |
| 87 | res.status = -1; |
| 88 | res.data ="send() sent a different number of bytes than expected"; |
| 89 | closesocket(sock); |
| 90 | return res; |
| 91 | } |
| 92 | |
| 93 | //get response |
| 94 | response = ""; |
| 95 | resp_leng= BUFFERSIZE; |
| 96 | while (resp_leng == BUFFERSIZE) |
| 97 | { |
| 98 | resp_leng= recv(sock, (char*)&buffer, BUFFERSIZE, 0); |
| 99 | if (resp_leng>0) |
| 100 | response+= string(buffer).substr(0,resp_leng); |
| 101 | //note: download lag is not handled in this code |
| 102 | } |
no test coverage detected