Reputation: 1885
I'm trying to teach myself Rust. I'm aware of rust-http, but I want to build my own http client. I'm using the currently nightly build for GNU Linux 64 bit.
Here's my current code:
use std::io::net::ip::SocketAddr;
use std::io::net::tcp::TcpStream;
use std::io::net::addrinfo::get_host_addresses;
use std::io::net::ip::IpAddr;
use std::io::stdio::println;
fn main() {
// HTTP endpoint
let host = ~"www.telize.com";
let path = ~"/geoip";
// Attempt to convert host to IP address
let ip_lookup = get_host_addresses(host).unwrap();
// Open socket connection
let addr = SocketAddr { ip: ip_lookup[0].clone(), port: port.clone() };
let mut socket = TcpStream::connect_timeout(addr, 200u64).unwrap();
// Format HTTP request
let mut header = format!("GET {} HTTP/1.0\r\nHost: {}\r\n", path.clone(), host.clone());
println(header);
socket.write_str(header);
// Make request and return response as string
let resp = socket.read_to_str().unwrap();
println(resp);
}
This compiles. However, running the code I see the HTTP request over the socket, but then it just hangs in the terminal. Also, there is no response. Testing this url (http://www.telize.com/geoip) in the browser returns a JSON response. How can I get this response (or any response) using the Rust std library? Thanks!!
Upvotes: 6
Views: 6633
Reputation: 90712
Your request is malformed in that you have not concluded the headers, and so it is waiting for you to do that. To conclude the headers, you need a blank line. That is, you must write an extra CRLF after the Host header.
(BTW, I don't see port
defined anywhere.)
Upvotes: 7
Reputation: 123260
Looks like everybody wants to build its own HTTP client w/o reading the documentation. Please have a look at RFC2616 and note especially the delimiter between HTTP header and body (even if there is no body).
Upvotes: 2