zoukankan      html  css  js  c++  java
  • python 之 模拟GET/POST提交

    以 POST/GET 方式向 http://127.0.0.1:8000/test/index 提交数据。

     1 # coding:utf-8
     2 import httplib
     3 import urllib
     4 
     5 class HttpClient(object):
     6     METHOD_POST = 'POST'
     7     METHOD_GET  = 'GET'
     8     REQUEST_HEADER = {'Content-type': 'application/x-www-form-urlencoded',
     9                       'Accept': 'text/plain'}
    10                    
    11     def __init__(self, host, port=80):
    12         self.host = host
    13         self.port = port
    14         
    15     def doPost(self, body, url='', headers=REQUEST_HEADER):
    16         return self._doRequest(self.METHOD_POST, urllib.urlencode(body), url, headers)
    17         
    18     def doGet(self, body=None, url='', headers={}):
    19         return self._doRequest(self.METHOD_GET, body, url, headers)
    20         
    21     def _doRequest(self, method, body, url, headers):
    22         try:
    23             conn = httplib.HTTPConnection(self.host, self.port)
    24             conn.request(method, url, body, headers)
    25             response = conn.getresponse()
    26             result = response.read()
    27             conn.close()
    28         except:
    29             raise
    30         finally:
    31             conn.close()
    32         return response.status, result
    33             
    34 def send():
    35     client = HttpClient('127.0.0.1', '8000')
    36     params = {'message': 'test',
    37               'username' : 'testUser',
    38               'password': 'testPwd'
    39               }
    40     print (client.doPost(params, '/test/index'))    # post方式    
    41     print (client.doGet(params, '/test/index'))     # get方式
    42     
    43 if __name__ == '__main__':
    44     send()

     第二种方法:

    import urllib
    import urllib2
    
    test_data = {'ServiceCode':'aaaa','b':'bbbbb'}   # get方法没有
    test_data_urlencode = urllib.urlencode(test_data) #get方法没有
    
    requrl = "http://127.0.0.1/test/index"
    
    req = urllib2.Request(url = requrl,data =test_data_urlencode)
    print req
    
    res_data = urllib2.urlopen(req)
    res = res_data.read()
    print res
  • 相关阅读:
    Apriori 算法-如何进行关联规则挖掘
    Nginx 常用命令
    Nginx Location匹配规则
    Nginx 负载均衡
    angular 路由传参的三种方式
    JAVA中final关键字的作用
    Python函数参数和注解是什么
    JMeter测试计划配置项解析
    JMeter元件作用域实践指南
    原来Python函数只是个对象
  • 原文地址:https://www.cnblogs.com/liuq/p/4642913.html
Copyright © 2011-2022 走看看