zoukankan      html  css  js  c++  java
  • perl6 HTTP::UserAgent (3) JSON

    如果一个 URL 要求POST数据是 JSON格式的, 那我们要怎么发送数据呢?

    第一种:

    HTTP::Request

    上一篇说到, 发送 POST 数据, 可以:

    1. $ua.post(url, %data)
    2. $request.add-form-data(%data)
        $ua.request($request)

    在这里, 无论是第一种方法还是第二种方法, 里面所发送的 %data 都会自动编码。

    JSON也是一种字符串格式, 这两种方法要求%data为一个hash, 那就说明这两种方法不能实现发送JSON。

    HTTP::Request 其实还有一种方法, 叫做:

    add-content

    些方法接受一个字符串的参数, 我们可以用这种方式提交JSON:

    > my $request = HTTP::Request.new(POST=>'http://localhost/')

    添加 JSON 字符串:

    > $request.content
    (Any)
    > %data = :user<root>, :password<root>
    {password => root, user => root}
    > $request.add-content(to-json(%data))
    Nil
    > $request.content
    { "password" : "root", "user" : "root" }
    >

    我这里用了 to-json (这方法在模块 JSON::Tiny中)把一个%data转化为一个 JSON字符串再传入$request中。

    之后再请求就行了:

    my $html = $ua.request($request)
    

     我们可以打印出请求参数看一下是不是真的发送了JSON格式字符串:

    > $html.request.Str
    POST / HTTP/1.1
    Host: localhost
    Content-Length: 40
    Connection: close
    
    { "password" : "root", "user" : "root" }
    
    >

    可以看到, 是发送了 JSON 格式的字符串数据。

    基实我们只要发送一个 JSON的字符串就行了, 我上面的代码, 只是为了方便, 把一个 %data 转化成了字符串, 其实我们可以定义一个 JSON 格式的字符串, 再 add-content 添加, 最后发送即可, 如下:

    先创建一个字符串:

    > my $post_string = '{"password":"root", "user":"root"}'

    添加进request对象并请求:

    > $request.add-content($post_string)
    Nil
    > $html = $ua.request($request)

    最后打印请求参数是否正确:

    > $html.request.Str
    POST / HTTP/1.1
    Host: localhost
    Content-Length: 34
    Connection: close
    
    {"password":"root", "user":"root"}
    
    >

    可以看到, 一样是能正常发送的。

    除了用 HTTP::Request 发送 JSON 请求外, PERL6还有一个模块:

    WWW

    这个模块可以接收字符串格式的POST数据, 也就是JSON了:

    multi jpost($url where URI:D|Str:D, *%form);
    multi jpost($url where URI:D|Str:D, %headers, *%form);
    multi jpost($url where URI:D|Str:D, Str:D $form-body, *%headers);
    
    say jpost 'https://httpbin.org/post?meow=moo', :72foo, :bar<♵>;
    say jpost 'https://httpbin.org/post?meow=moo',
            %(Content-type => 'application/json'), :72foo, :bar<♵>;

    用它发送请求, 可以像这样:

    jpost 'http://localhost', JSON, %headers;

    这是 jpost 请求, 会自动获取 JSON 格式的 返回值, 如果要获取一般格式的响应请求, 可以用它的 POST 方法。

    WWW 模块在如下地址可找到:

    https://github.com/zoffixznet/perl6-WWW

    我们可以看下它的 POST 源码, 其实也是用了 HTTP::Request进行了封装而已:

     

  • 相关阅读:
    mongo批量删除js示例
    Mongo压测介绍
    线性代数学习笔记(1)--二维向量点积本质(仅供自己理解)
    墨菲定律的正确解读
    spring cloud 2020.0.1踩坑记录-bootstrap不生效等
    记一次网络质量原因导致接口调用超时的调查过程
    .NET Debugging Demos Lab 2: Crash
    .NET Debugging Demos Lab 3: Memory
    Hang caused by GC
    .NET Debugging Demos Lab 4: High CPU hang
  • 原文地址:https://www.cnblogs.com/perl6/p/7435437.html
Copyright © 2011-2022 走看看