使用Common Lisp usocket发送http请求时出现400 Bad Request

时间:2013-08-02 05:22:31

标签: http lisp httprequest common-lisp usocket

我正在使用以下代码来抓取网址http://brandonhsiao.com/essays.html

(defparameter *new-line* '(#\Return #\Newline))

(defun read-url (host port path)
  (let ((sock (usocket:socket-connect host port)))
    (format (usocket:socket-stream sock) "~A"
            (concatenate 'string
                         "GET " path " HTTP/1.1" *new-line*
                         "Connection: close" *new-line* *new-line*))
    (force-output (usocket:socket-stream sock))
    (do ((line
           (read-line (usocket:socket-stream sock) nil)
           (read-line (usocket:socket-stream sock) nil))
         (all ""))
      ((not line) all)
      (setf all (concatenate 'string all line *new-line*)))))

(print (read-url "brandonhsiao.com" 80 "/essays.html"))

这给了我一个400 Bad Request错误,但是当我使用Firefox访问http://brandonhsiao.com/essays.html时,一切都很好。我做错了什么?

1 个答案:

答案 0 :(得分:1)

看起来我需要包含主机。

(defparameter *new-line* '(#\Return #\Newline))

(defun read-url (host port path)
  (let ((sock (usocket:socket-connect host port)))
    (format (usocket:socket-stream sock) "~A"
            (concatenate 'string
                         "GET " path " HTTP/1.1" *new-line*
                         "Host: " host *new-line* *new-line*))
    (force-output (usocket:socket-stream sock))
    (do ((line
           (read-line (usocket:socket-stream sock) nil)
           (read-line (usocket:socket-stream sock) nil))
         (all ""))
      ((not line) all)
      (setf all (concatenate 'string all line " ")))))