Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Racket中从REPL发出HTTP GET_Http_Scheme_Racket_Read Eval Print Loop - Fatal编程技术网

在Racket中从REPL发出HTTP GET

在Racket中从REPL发出HTTP GET,http,scheme,racket,read-eval-print-loop,Http,Scheme,Racket,Read Eval Print Loop,我觉得我遗漏了一些东西,但在阅读了net/url文档并大致浏览了一遍之后,我无法找到从交互式提示符发出GET请求的方法。基本上,我想模仿我的python工作流程来浏览网站: response = urlopen("http://www.someurl.com") 这在球拍上可行吗 试试这个: (require net/url) (define input (get-pure-port (string->url "http://www.someurl.com"))) (define re

我觉得我遗漏了一些东西,但在阅读了net/url文档并大致浏览了一遍之后,我无法找到从交互式提示符发出GET请求的方法。基本上,我想模仿我的python工作流程来浏览网站:

response = urlopen("http://www.someurl.com")
这在球拍上可行吗

试试这个:

(require net/url)

(define input (get-pure-port (string->url "http://www.someurl.com")))
(define response (port->string input))
(close-input-port input)
现在,
response
变量将包含来自服务器的http响应。更好的是,将上述内容打包到一个过程中,还请注意,我添加了允许的最大重定向数:

(define (urlopen url)
  (let* ((input (get-pure-port (string->url url) #:redirections 5))
         (response (port->string input)))
    (close-input-port input)
    response))

(urlopen "http://www.someurl.com") ; this will return the response
编辑:

根据@GregHendershott的优秀建议(详见他的答案),下面是实现所需功能的另一种更健壮的方法:

(define (urlopen url)
  (call/input-url
   (string->url url)
   (curry get-pure-port #:redirections 5)
   port->string))
使用有几个优点:

  • 您不需要自己关闭端口
  • 即使出现异常,端口也会关闭
  • 它的第三个参数是
    (输入端口?->any/c)
    ——也就是说,一个接受
    输入端口
    并返回任何内容的函数。除了您自己编写的函数外,这可能是一个已经定义的函数,如
    端口->字符串
    将html读取为xml
    ,等等
例如:

(call/input-url (string->url "http://www.google.com/")
                get-pure-port
                port->string)
注意:当我输入这个答案时,我注意到Óscar编辑了他的ToDo重定向。我的类似编辑是:

(call/input-url (string->url "http://www.google.com/")
                (curry get-pure-port #:redirections 4)
                port->string)

当然,这两种方法都非常冗长,无法在REPL中频繁键入。因此,Óscar建议定义自己的
url open
函数是一个很好的建议。我认为,使用
调用/输入url实现它将是更好的选择。

除了“手动”解析标题外,还有其他方法提取状态代码吗?我很惊讶,我在racket本身或您的http库中都找不到任何帮助函数来做这件事。很抱歉,直到现在我才注意到您的评论!My http lib具有执行此操作的函数: