前言
有些接口請求頭部帶上X-Requested-With:XMLHttpRequest ,返回數據是 json 。如果頭部不加這個參數,返回數據是普通 html 文本。
這種頭部帶上X-Requested-With:XMLHttpRequest的是 Ajax 異步請求。
Ajax 請求
Ajax 即 “Asynchronous Javascript And XML”(異步 JavaScript 和 XML),是指一種創建交互式、快速動態網頁應用的網頁開發技術,無需重新加載整個網頁的情況下,能夠更新部分網頁的技術。
通過在后台與服務器進行少量數據交換,Ajax 可以使網頁實現異步更新。這意味着可以在不重新加載整個網頁的情況下,對網頁的某部分進行更新。
那么服務器如何判斷request來自Ajax請求(異步)還是傳統http請求(同步)?
1、傳統同步請求參數
accept */*
accept-charset gb2312,utf-8;q=0.7,*;q=0.7
accept-encoding gzip,deflate
accept-language zh-cn,zh;q=0.5
cache-control max-age=0
connection keep-alive
cookie JSESSIONID=1A3BED3F593EA9747C9FDA16D309AF6B
keep-alive 300
user-agent Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.15) Gecko/2009101601 Firefox/3.0.15 (.NET CLR 3.5.30729)
2、Ajax 異步請求方式
accept */*
accept-charset gb2312,utf-8;q=0.7,*;q=0.7
x-requested-with XMLHttpRequest
accept-encoding gzip,deflate
accept-language zh-cn,zh;q=0.5
cache-control max-age=0
connection keep-alive
cookie JSESSIONID=1A3BED3F593EA9747C9FDA16D309AF6B
keep-alive 300
user-agent Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.15) Gecko/2009101601 Firefox/3.0.15 (.NET CLR 3.5.30729)
可以看到 Ajax 請求多了個 x-requested-with
場景案例
登錄禪道網站,輸入賬號和密碼后
使用fiddler抓包看請求參數,頭部會有個參數:X-Requested-With: XMLHttpRequest
,返回的是json數據: {"result":"success","locate":"\/zentao\/"}
使用requests發請求,如果頭部不帶參數:X-Requested-With: XMLHttpRequest
import requests
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
url = "http://49.235.x.x:8081/zentao/user-login.html"
body = {
"account": "admin",
"password": "yoyo123456",
"passwordStrength": 1,
"referer": "/zentao/",
"verifyRand": "1014015280",
"keepLogin": 1
}
r = requests.post(url, data=body)
print(r.text)
# 返回html
# <html><meta charset='utf-8'/><style>body{background:white}</style><script>self.location='/zentao/';
# </script>
使用requests發請求, 頭部帶上參數:X-Requested-With: XMLHttpRequest
,模擬 Ajax 異步請求
import requests
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
url = "http://49.235.x.x:8081/zentao/user-login.html"
h = {
"X-Requested-With": "XMLHttpRequest"
}
body = {
"account": "admin",
"password": "yoyo123456",
"passwordStrength": 1,
"referer": "/zentao/",
"verifyRand": "1014015280",
"keepLogin": 1
}
r = requests.post(url, headers=h, data=body)
print(r.text)
# 返回json
# {"result":"success","locate":"\/zentao\/"}
此時就可以返回json數據了