zoukankan      html  css  js  c++  java
  • curl perl python 模拟post请求

    [elk@node01 ~]$ curl -d "username=99999@zjtlcb.com&password=1234567" http://192.168.137.1:8000/api2/auth-token/
    {"token": "0ac9e8585ef6ae51eb62c785d10a6c5102de3ff7"}[elk@node01 ~]$ 
    
      -d/--data <data>
    
    (HTTP)发送指定的数据以一个POST请求到HTTP server,和用户填写衣蛾HTML表单和按下submit按钮一样
    
     这个会导致curl 传递数据到server使用content-type application/x-www-form-urlencoded.  
    
    
    perl 版:
    
    [elk@node01 ~]$ cat a2.pl 
    use  LWP::UserAgent; 
    use LWP;
    use Encode;
    use LWP::Simple;
    use LWP::UserAgent;
    use HTTP::Cookies;
    use HTTP::Headers;
    use HTTP::Response;
    use Encode;
    use URI::Escape;
    use URI::URL;
    use JSON;
      my $ua = LWP::UserAgent->new;
      $ua->agent("Mozilla/5.0 (Windows NT 6.1; rv:30.0) Gecko/20100101 Firefox/30.0");
      my $cookie_jar = HTTP::Cookies->new(
         file=>'lwp_cookies.txt',
         autosave=>1,
         ignore_discard=>1);
         $ua->cookie_jar($cookie_jar);
       my $token_url= ' http://192.168.137.1:8000/api2/auth-token/';
                    
      
       my $res = $ua->post($token_url,
                    {
                    'username'=>'99999@zjtlcb.com',
                    'password'=>'1234567'
                    });
       print $res->content();
       print "
    ";
       my $r= $res->content();
       my $r=encode_utf8($r);
       my $hash = decode_json($r);
       print $hash->{"token"};
    [elk@node01 ~]$ perl a2.pl 
    {"token": "0ac9e8585ef6ae51eb62c785d10a6c5102de3ff7"}
    0ac9e8585ef6ae51eb62c785d10a6c5102de3ff7[elk@node01 ~]$ 
    
    
    python 版:
    def gettoken():
        data = {'username': '99999@zjtlcb.com', 'password': '1234567'}
        post_data = urllib.urlencode(data)  # 将post消息化成可以让服务器编码的方式
        cj = cookielib.CookieJar()  # 获取cookiejar实例
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        # 自己设置User-Agent(可用于伪造获取,防止某些网站防ip注入)
        headers = {}
        website = "http://127.0.0.1:8000/api2/auth-token/"
        req = urllib2.Request(website, post_data, headers)
        content = opener.open(req)
        s = content.read()  # linux下没有gbk编码,只有utf-8编码
        print s
        print type(s)
    gettoken()
    
    C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/Django/a4.py
    {"token": "0ac9e8585ef6ae51eb62c785d10a6c5102de3ff7"}
    <type 'str'>

  • 相关阅读:
    VS2015&windows开发环境配置
    Chapter 12. Classes
    Chapter 11. Generic Algorithms
    Chapter 10. Associative Containers
    Chapter 9. Sequential Containers
    Chapter 8. The IO Library
    Chapter 7. Functions
    Chapter 5. Expressions
    案例分析 极化跳变
    机器如果能够实现自己建模,应该是下一次人工智能的飞跃点
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13349509.html
Copyright © 2011-2022 走看看