0

我正在使用以下代码来获取 url 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错误,但是当我http://brandonhsiao.com/essays.html使用 Firefox 访问时,一切都很好。我究竟做错了什么?

4

1 回答 1

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 " ")))))
于 2013-08-02T05:44:52.777 回答