He acabado los examenes.
Aquí esta el código:
/*Text based web browser*/
#include <string>
#include <iostream>
#include <boost/asio.hpp>
using namespace std;
string get_formated_web(string);
string getWeb(string);
string getPage(string);
int main(int argv, char **argc){
if(argv==2){
string web=getWeb(string(argc[1]));
cout<<"web: "<<web<<endl;
string page=getPage(string(argc[1]));
cout<<"page: "<<page<<endl;
boost::asio::ip::tcp::iostream stream;
stream.expires_from_now(boost::posix_time::seconds(60));
stream.connect(web, "http");
stream << "GET "<<page<<" HTTP/1.0\r\n";
stream << "Host: "<< web <<"\r\n";
stream << "Accept: */*\r\n";
stream << "Connection: close\r\n\r\n";
stream.flush();
stringstream codestream;
codestream<<stream.rdbuf();
string htmlsource( codestream.str() );
string formatedweb=get_formated_web(htmlsource);
std::cout << formatedweb;
}
else{
cout<<"Wrong arguments."<<endl
<<"Usage: http www.webpage.com"<<endl;
}
}
/* given: www.webpage.com/page.html */
/* returns: www.webpage.com */
string getWeb(string a){
string web;
for(int i=0;i<a.size();i++){
if(a[i]==':'){
web+=a[i];
if(i+2<a.size()){
if(a[i+1]=='/' && a[i+2]=='/'){
web+="//";
i+=2;
}
}
}
else if(a[i]=='/'){
return web;
}
else{
web+=a[i];
}
}
return web;
}
/* given: www.webpage.com/page.html */
/* returns: /page.html */
string getPage(string a){
string page;
bool found=false;
for(int i=0;i<a.size();i++){
if(found){
page+=a[i];
}
else{
if(a[i]==':'){
if(i+2<a.size()){
if(a[i+1]=='/' && a[i+2]=='/') i+=2;
}
}
else if(a[i]=='/'){
page+='/';
found=true;
}
else{}
}
}
if(page=="") return "/";
return page;
}
/* given: html source code */
/* returns: formatted text webpage */
string get_formated_web(string unformated){
return unformated;
}
No es un navegador completo pero espero que se vea clara la idea principal.
Lo que hacemos es imprimir el código fuente html.
La función get_formated_text() pretende traducir el html a el text legible.
Por ejemplo si le pasas:
<html>
<body>
<p>hola</p>
</body>
</html>
Te devuelve:
He usado la libreria no estándar asio la cual es parte de boost.
En g++ se puede compilar así(como no es estándar toca linkear):
g++ http.cpp -lboost_system
Te animo a que completes el código a tu gusto o que por lo menos te sirva un poco de guía.