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
  • 相关阅读:
    windows 内存泄露和资源泄漏调试
    window驱动
    Direct2D教程(七)单色画刷
    Direct2D教程(三)简单几何图形
    求反射向量
    Visual Studio 2012中使用自定义project properties
    View Transform(视图变换)详解
    八进制字符与十六进制字符
    Direct2D教程(四)Path Geometry
    C++默认构造函数
  • 原文地址:https://www.cnblogs.com/liuq/p/4642913.html
Copyright © 2011-2022 走看看