【工作日記11】python+post

繼昨天的POST請求返回值不一致的問題,今天又被卡了挺久,不知道排查的思路,後面同事提醒了下,進行抓包看看構造出來的POST請求發的數據是否和web端發出的post請求是一樣的。

使用wireshark對web端發送的POST請求和使用python構造的post請求 分別抓包,結果如下:

如圖:

左邊爲web端發送的,右邊自己構造的。可以看出,主要的不同點就是post數據那一塊。

發現是數據那塊的問題,那就嘗試使用不同的方法處理數據,因爲這個數據是json格式的,所以搜了下處理json格式的庫,

之前是這麼幹的:

  url = 'http://%s/cgi-bin/fat_ap.cgi'%ip
    headers = {
        "POST":"/cgi-bin/fat_ap.cgi HTTP/1.1",
        "Host":"%s"%ip,
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
        'Accept-Encoding': 'gzip, deflate',
        'Content-Type': 'application/json',
        'Access-Control-Allow-Headers': '*',
        'Content-Length':'77',
        'Origin': 'http://192.23.35.2',
        'Connection': 'close',
        'Referer': 'http://192.23.35.2/index.html'
    }
    values = {
        "opr":"login",
        "account":"admin",
        "passwd":"%s"%password_md5
    }
 
 
    values = json.dumps(values)
    print(url,values,headers)
    data = urllib.parse.quote_plus(values).encode('utf-8')
    request = urllib.request.Request(url, data, headers)
    html = urllib.request.urlopen(request).read().decode('utf-8')
    print(html)

數據values使用json.dumps將字典形式的數據轉化爲字符串,再使用urllib庫。

嘗試換個庫,使用requests庫:

  url = 'http://%s/cgi-bin/fat_ap.cgi'%ip
    headers = {
        "POST":"/cgi-bin/fat_ap.cgi HTTP/1.1",
        "Host":"%s"%ip,
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
        'Accept-Encoding': 'gzip, deflate',
        'Content-Type': 'application/json',
        'Access-Control-Allow-Headers': '*',
        'Content-Length':'77',
        'Origin': 'http://192.23.35.2',
        'Connection': 'close',
        'Referer': 'http://192.23.35.2/index.html'
    }
    values = {
        "opr":"login",
        "account":"admin",
        "passwd":"%s"%password_md5
    }
 
 
    " 
    values = json.dumps(values)
    print(url,values,headers)
    data = urllib.parse.quote_plus(values).encode('utf-8')
    request = urllib.request.Request(url, data, headers)
    html = urllib.request.urlopen(request).read().decode('utf-8')
    print(html)
    "

    values = json.dumps(values)
    html =requests.post(url, values , headers)
    print(html)

其餘不變,就把使用requests.post庫,還不用另外編碼解碼,發送之後發現終於是想要的效果了。

這兩者的區別到底是啥呢?哪位大佬指導指導。

區別可參考:https://www.cnblogs.com/liuchaodada/p/12050745.html

看完區別,總體就是requests是對urllib的再次封裝,使用更便捷,所以按理來說urllib應該也能實現相同的效果,可以之後嘗試以下,方法可以參考https://www.cnblogs.com/php-linux/p/8818436.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章