美文网首页
python发送post和get请求

python发送post和get请求

作者: 是归人不是过客 | 来源:发表于2018-07-26 10:34 被阅读70次

    get请求:

    使用get方式时,请求数据直接放在url中。

    方法一、

    import urllib

    import urllib2

    url = "http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa"

    req = urllib2.Request(url)

    print req

    res_data = urllib2.urlopen(req)

    res = res_data.read()

    print res

    方法二、

    import httplib

    url = "http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa"

    conn = httplib.HTTPConnection("192.168.81.16")

    conn.request(method="GET",url=url)

    response = conn.getresponse()

    res= response.read()

    print res

    post请求:

    使用post方式时,数据放在data或者body中,不能放在url中,放在url中将被忽略。

    方法一、

    import urllib

    import urllib2

    test_data = {'ServiceCode':'aaaa','b':'bbbbb'}

    test_data_urlencode = urllib.urlencode(test_data)

    requrl = "http://192.168.81.16/cgi-bin/python_test/test.py"

    req = urllib2.Request(url = requrl,data =test_data_urlencode)

    print req

    res_data = urllib2.urlopen(req)

    res = res_data.read()

    print res

    方法二、

    import urllib

    import httplib

    test_data = {'ServiceCode':'aaaa','b':'bbbbb'}

    test_data_urlencode = urllib.urlencode(test_data)

    requrl = "http://192.168.81.16/cgi-bin/python_test/test.py"

    headerdata = {"Host":"192.168.81.16"}

    conn = httplib.HTTPConnection("192.168.81.16")

    conn.request(method="POST",url=requrl,body=test_data_urlencode,headers = headerdata) 

    response = conn.getresponse()

    res= response.read()

    print res

    相关文章

      网友评论

          本文标题:python发送post和get请求

          本文链接:https://www.haomeiwen.com/subject/jlvvmftx.html