Skip to content
Find file
Fetching contributors…
Cannot retrieve contributors at this time
executable file 138 lines (117 sloc) 2.2 KB
#ifndef com_sleepless_httprequest_cpp
#define com_sleepless_httprequest_cpp
// Copyright 2009 Sleepless Software Inc. All Rights Reserved
#include "string.cpp"
#include "socket.cpp"
#include "url.cpp"
/*
HTTPRequest hr(url);
if(hr.isConnected())
{
if(hr.sendRequest("Foo: bar\n", "GET") == -1)
throw new NetError("error sending request headers");
int n = hr.readheaders();
if(hr.rcode < 200 || hr.rcode > 299)
throw new NetError("http server error: %d", hr.rcode);
while(true)
{
n = read(buf, sizeof(buf));
if(n == -1)
throw new NetError("read error");
if(n == 0)
break; // EOF
fetched += n;
}
}
*/
struct HTTPRequest
{
Socket *sock;
int port;
S host;
S path;
int clen;
int cred;
S rtext;
int rcode;
float progress()
{
float p = 0.0f;
if(clen > 0)
p = (float)((cred * 100) / clen);
return p;
}
int avail()
{
return sock->available();
}
int read(unsigned char *buf, int len)
{
int n = clen - cred;
if(n < 1)
return 0;
int r = sock->read(buf, len);
if(r > 0)
cred += r;
if(r == 0)
sock->disconnect(); // end of stream, might as well close it
return r;
}
int readHeaders()
{
char line[100];
int r = 0;
while(true)
{
int n = sock->readLine(line, sizeof(line));
if(n < 1)
break;
r += n;
if(strcmp(line, "\n") == 0)
break; // end of headers
if(sscanf(line, "HTTP/%*[^ ] %d %*[^\n]", &rcode) == 1)
rtext = line;
if(strncasecmp(line, "Content-Length: ", 16) == 0)
clen = atol(line + 16);
}
return r;
}
int sendRequest(const char *hdrs = 0, const char *m = "GET")
{
S method(m);
bool ssl = (port == 443);
if(ssl)
return -1; // XXX
if(method != "GET")
return -1; // XXX
S req;
req.cat(S(method, " /", path, " HTTP/1.0\n"));
req.cat(S("Host: ", host, "\n"));
if(hdrs)
req.cat(hdrs);
req.cat("\n");
return sock->writeStr(req);
}
bool isConnected()
{
return sock->isConnected();
}
HTTPRequest(const char *us)
{
port = 0;
clen = 0;
cred = 0;
rcode = 0;
URL url(us);
host = url.host;
port = url.port;
path = url.path;
sock = new Socket(host, port);
}
~HTTPRequest()
{
if(sock)
delete sock;
}
};
#endif // com_sleepless_httprequest_cpp
Jump to Line
Something went wrong with that request. Please try again.