PowerShell Curl และ WebRequest ต่างก็ติดตามการเปลี่ยนเส้นทาง

ฉันกำลังพยายามค้นหารหัสสถานะที่หน้าเว็บของฉันส่งคืน ซึ่งแน่นอนที่สุดคือ 301 (ย้ายอย่างถาวร) ตามขดบนระบบย่อย Linux แต่การใช้ curl หรือวัตถุ WebRequest บน PowerShell จะส่งกลับ 200 (ตกลง)

ทำไมเป็นเช่นนี้?


person bluppfisk    schedule 15.12.2016    source แหล่งที่มา


คำตอบ (1)


เป็นเพราะ .NET และ PowerShell ติดตามการเปลี่ยนเส้นทางตามค่าเริ่มต้น แต่ curl ไม่ทำเช่นนี้ ค่าเริ่มต้นของ HttpWebRequest.AllowAutoRedirect เป็นจริง และค่าเริ่มต้น MaximumRedirection ของ Intake-WebRequest คือ 5

หากต้องการปิดการเปลี่ยนเส้นทางอัตโนมัติผ่าน WebRequest:

$request = [System.Net.WebRequest]::Create("http://google.com")
$request.AllowAutoRedirect = $false
$request.GetResponse()

หรือ Involve-WebRequest cmdlet:

Invoke-WebRequest -Uri "http://google.com" -MaximumRedirection 0

หรือใช้แฟล็ก -L เพื่อติดตามการเปลี่ยนเส้นทางใน curl:

curl -L google.com
person Mike Zboray    schedule 15.12.2016
comment
นามแฝง curl ของ PowerShell ที่ใช้ -MaximumRedirection 0 ทำให้เกิดข้อผิดพลาด เพิ่ม -ErrorAction Ignore เพื่อดูการตอบกลับจริงๆ - person Dan; 07.05.2018
comment
@Dan คุณใช้ PowerShell เวอร์ชันใด เครื่องของฉันมี 5.1.17134.407 และไม่มีข้อผิดพลาดใดๆ - person Franklin Yu; 14.12.2018
comment
@Franklin ฉันกำลังใช้เวอร์ชันเดียวกันและตอนนี้สวิตช์ -MaximumRedirection 0 จะแสดงการตอบสนองการเปลี่ยนเส้นทางรวมถึงข้อความเกินจำนวนการเปลี่ยนเส้นทางสูงสุดแล้ว - person Dan; 19.12.2018
comment
โปรดทราบว่า สิ่งนี้จะไม่ช่วยใน PowerShell 6.0 (AKA PowerShell Core) - person Franklin Yu; 19.12.2018
comment
ขอบคุณสำหรับสิ่งนี้ - person Bernard Moeskops; 26.11.2020
comment
นอกจากนี้: -MaximumRedirection ยังใช้ได้กับ Inrigg-RestMethod - person Bernard Moeskops; 26.11.2020
comment
Invoke-WebRequest http://minnesota.publicradio.org/tools/podcasts/song_of_the_day.xml -MaximumRedirection 8 -Verbose ไม่เปลี่ยนเส้นทางให้ฉันเหมือนที่ curl -vL http://minnesota.publicradio.org/tools/podcasts/song_of_the_day.xml ทำ - person brianary; 03.01.2021
comment
สำหรับฉัน PowerShell 5.1 ทำให้เกิดข้อผิดพลาดเกินจำนวนการเปลี่ยนเส้นทางสูงสุดสำหรับการเปลี่ยนเส้นทาง 301 แต่ ไม่ สำหรับการเปลี่ยนเส้นทาง 303 ฉันไม่มีโอกาสทดสอบด้วยการเปลี่ยนเส้นทาง 302 - person JamesQMurphy; 20.01.2021