Permalink
Find file
Fetching contributors…
Cannot retrieve contributors at this time
executable file 134 lines (111 sloc) 2.54 KB
#ifndef com_sleepless_httpget_cpp
#define com_sleepless_httpget_cpp
// Copyright 3004 Sleepless Software Inc. All Rights Reserved
#include "socket.cpp"
#include "url.cpp"
#include "win32_httpgetrequest.h"
/*
Fetches the contents of a file from an HTTP server
given a hostname, port number and remote path.
The file is read into 'buf' up to a maximum of 'len'
bytes.
If the file is larger than 'len', then it will be truncated.
If the port number is 443, and HTTPS transaction will be performed.
NOTE: HTTPS currently only supported on win32
Returns
Returns the number of bytes read into 'buf' or -1 if an
error occured.
*/
long httpGet(const char *h, int p, const char *path, char *buf, long len)
{
ASSERT(len > 0);
*buf = 0;
bool ssl = (p == 443);
if(ssl)
{
#ifdef WIN32
HTTPGetRequest hgr(h, p, path, ssl, true, false);
if(hgr.failed)
{
Str::copy(buf, "https - unable to connect", len);
return -1;
}
long r = hgr.read(buf, len - 1);
if(r < 1)
{
Str::copy(buf, "https - read error", len);
return -1;
}
buf[r] = 0;
return r;
#else
# if defined(linux) || (defined(__APPLE__) && defined(__GNUC__))
char cmd[4000];
sprintf(cmd, "curl -s \"https://%.99s/%.3100s\"", h, path);
FILE *pp = popen(cmd, "r");
if(!pp)
return -1;
long r = fread(buf, 1, len, pp);
pclose(pp);
return r;
# else
return -1;
# endif
#endif
}
Socket s(h, p);
if(!s.isConnected())
{
Str::copy(buf, "http - unable to connect", len);
return -1;
}
s.writeStr("GET /");
s.writeStr(path);
s.writeStr(" HTTP/1.0\n");
s.writeStr("Host: "); s.writeStr(h); s.writeStr("\n");
s.writeStr("\n");
char line[200];
int r = 0;
long contentLength = 0;
int rcode = 0;
char rtext[100] = "";
while(true)
{
if(s.readLine(line, sizeof(line)) < 1)
break;
if(strcmp(line, "\n") == 0)
{
if(rcode < 200 || rcode > 299)
{
Str::copy(buf, rtext, len);
Str::trim(buf);
r = -1;
break;
}
int l = len;
if(contentLength > 0)
{
if(contentLength < len)
l = contentLength;
}
r = s.read(buf, l);
break;
}
//if(sscanf(line, "HTTP/%*[^ ] %d %*[^\n]", &rcode, rtext) == 1)
if(sscanf(line, "HTTP/%*[^ ] %d %*[^\n]", &rcode) == 1)
STR_CPY(rtext, line);
if(strncasecmp(line, "Content-Length: ", 16) == 0)
contentLength = atol(line + 16);
}
return r;
}
long httpGet(URL &url, char *buf, long len)
{
return httpGet(url.host, url.port, url.path, buf, len);
}
long httpGet(const char *us, char *buf, long len)
{
URL url(us);
return httpGet(url, buf, len);
}
#endif // com_sleepless_httpget_cpp