import { IncomingMessage } from "http" import { fetch } from "bun" import https from "https" import fs from "fs" const maxNum = 3 function request(opts: any, cb: any, num = 0) { https.get(opts, function (res: IncomingMessage) { if (res.statusCode === 302) { if (num > maxNum) { console.error("重定向次数超过三次,已强制终止"); return } let url = new URL(res.headers['location']!) if (url) { console.log(`重定向:`, url.href); num++ // 重定向 request({ ...opts, hostname: url.hostname, path: url.pathname + url.search, }, cb, num) } } else if (res.statusCode === 200) { cb && cb(res) } else { console.log(`当前${opts.hostname}请求${opts.path}未成功`, res.statusCode); // res.on('data', (d) => { // process.stdout.write(d); // }); } }) } // 会重定向,需要想重定向请求 request({ hostname: "api.zzzmh.cn", path: "/v2/bz/v3/getUrl/1b87e2c5880511ebb6edd017c2d2eca211", headers: { 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', // "User-Agent": getRandomUserAgent(), // 'Connection': 'keep-alive', 'Referer': 'https://bz.zzzmh.cn/' } }, function (res: IncomingMessage) { const write = fs.createWriteStream("./a.jpg") res.pipe(write) write.on("error", function (err) { console.log(err) }) })