I am trying to use HTTP post request to get the location info from google geolocation API but something is going wrong with the connection after I send the query i get 0 as return value for recev() Is the way am sending post request the issue? why does the connection close after I send the request? what should i do to keep the connection alive?
What I have tried:
#include <windows.h>
#include <winsock.h>
#include <string.h>
#pragma comment(lib, "Ws2_32.lib")
char content[1500];
#define constGLReq \
"POST /geolocation/v1/geolocate?key=AIzaSyBibyFS6jV3OgPxIZkFp_t97G_THjrq0Z4; sensor=false HTTP/1.1\r\n" \
"Host: www.googleapis.com\r\n" \
"Connection: close\r\n" \
"Cache-Control: no-cache\r\n" \
"Connection: keep-alive\r\n" \
"Content-Type: application/json\r\n" \
"Content-Length: 0\r\n" \
"\r\n"
int main()
{
char data[512];
SOCKET Socket;
int Res ;
WSADATA wsaData;
char * host = "www.googleapis.com";
struct hostent *server;
SOCKADDR_IN Socaddr;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
return -1;
}
memset(data, 0, sizeof(data));
memset(content, 0, sizeof(content));
Socket = socket(AF_INET, SOCK_STREAM, 0);
if (Socket == INVALID_SOCKET)
{
}
server = gethostbyname(host);
memset(&Socaddr, 0, sizeof(SockAddr));
Socaddr.sin_port = htons(443);
Socaddr.sin_family = AF_INET;
memcpy(&Socaddr.sin_addr.s_addr, server->h_addr, server->h_length);
Res = connect(Socket, (SOCKADDR*)(&Socaddr), sizeof(Socaddr));
if (Res != 0)
{
closesocket(Socket1);
}
else
{
Res = send(Socket, constGLReq, (int)strlen(constGLReq), 0);
if (Res == SOCKET_ERROR)
{
closesocket(Socket1);
}
else if (Res <= 0)
{
}
else `enter code here`
{
do
{
Res = recv(Socket, data, sizeof(data), 0);
error = WSAGetLastError();
if (strlen(data) != 0)
{
if (strlen(content) == 0)
{
strcpy(content, data);
}
else
{
strcat(content, data);
}
}
memset(data, 0, sizeof(data));
} while (Res > 0);
}
}
closesocket(Socket1);
WSACleanup();
return 0;
}