7

How can I get an html response from a url string? Using this:

#lang racket
(require net/url)
(require net/websocket/client)
(define google (string->url "http://google.com"))

(ws-connect(struct-copy url google [scheme "ws"]))

Gives me ws-connect: Invalid server handshake response. Expected #"\242\266\336\364\360\"\21~Y\347w\21L\2326\"", got #"<!DOCTYPE html>\n"

Jack
  • 2,223
  • 13
  • 23
kim taeyun
  • 1,837
  • 2
  • 24
  • 49
  • possible duplicate of [How do I read a web page in Racket?](http://stackoverflow.com/questions/14016254/how-do-i-read-a-web-page-in-racket) – Sridhar Ratnakumar Sep 25 '14 at 00:14

1 Answers1

11

I'm assuming you just want to do the equivalent of an HTTP GET.

(require net/url)
(define google (string->url "http://google.com"))

Use get-pure-port to do HTTP GET; it returns an input port. Also, the URL above redirects, so we have to enable following redirections.

(define in (get-pure-port google #:redirections 5))

If you want the response as a single string you can use port->string:

(define response-string (port->string in))
(close-input-port in)

Or you could pass it to some function that parses it as HTML or XML. There are several such libraries on PLaneT; I recommend (planet neil/html-parsing:1).

See also call/input-url, which automatically handles closing the port.

Ryan Culpepper
  • 10,495
  • 4
  • 31
  • 30