http.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. // 发送GET请求
  2. const {logger} = require("./logger");
  3. const http = require('http');
  4. const https = require('https');
  5. const fs = require("fs");
  6. //公共的请求头
  7. function getHeaders(headers, body) {
  8. if (body.length !== 0) {
  9. headers['Content-Length'] = Buffer.byteLength(body)
  10. }
  11. headers['Content-Type'] = 'application/json'
  12. return headers
  13. }
  14. function request_get(url, headers) {
  15. return new Promise((resolve, reject) => {
  16. var callback = function (res) {
  17. let data = '';
  18. // 监听数据事件来收集响应数据
  19. res.on('data', (chunk) => {
  20. data += chunk;
  21. });
  22. // 监听结束事件来处理响应结束
  23. res.on('end', () => {
  24. // logger.info(`响应体: ${data}`);
  25. resolve(data);
  26. });
  27. }
  28. var errorback = function errorback(e) {
  29. // logger.error(`请求遇到问题: ${e.message}`);
  30. reject(e);
  31. }
  32. // POST 请求的选项
  33. const options = {
  34. method: 'GET',
  35. headers: getHeaders(headers, "")
  36. };
  37. let httpsReq = null
  38. if (!url.includes("https")) {
  39. httpsReq = http.request(url, options, callback).on('error', errorback);
  40. } else {
  41. httpsReq = https.request(url, options, callback).on('error', errorback);
  42. }
  43. // 不要忘了关闭请求,以防止内存泄漏
  44. httpsReq.end();
  45. });
  46. }
  47. function request_post(url, param, headers) {
  48. return new Promise((resolve, reject) => {
  49. var callback = function (res) {
  50. let data = '';
  51. // 监听数据事件来收集响应数据
  52. res.on('data', (chunk) => {
  53. data += chunk;
  54. });
  55. // 监听结束事件来处理响应结束
  56. res.on('end', () => {
  57. // logger.info(`响应体: ${data}`);
  58. resolve(data);
  59. });
  60. }
  61. var errorback = function errorback(e) {
  62. // logger.error(`请求遇到问题: ${e.message}`);
  63. reject(e);
  64. }
  65. // POST 请求的数据
  66. const postData = JSON.stringify(param);
  67. // logger.info('请求参数:', postData, headers);
  68. // POST 请求的选项
  69. // logger.info('请求头:', headers);
  70. const options = {
  71. method: 'POST',
  72. headers: getHeaders(headers, postData)
  73. };
  74. var postReq = null;
  75. if (!url.includes("https")) {
  76. postReq = http.request(url, options, callback).on('error', errorback);
  77. } else {
  78. postReq = https.request(url, options, callback).on('error', errorback);
  79. }
  80. // 写入数据到请求体
  81. postReq.write(postData);
  82. // 结束请求
  83. postReq.end();
  84. })
  85. }
  86. function dowFile(url, fileName, dowPath, headers) {
  87. return new Promise((resolve, reject) => {
  88. // 设定您想要下载的宝藏(文件)的位置
  89. const fileUrl = url + "/" + fileName;
  90. // 指定要将下载的宝藏存放在何处(本地路径)
  91. const filePath = dowPath + "/" + fileName;
  92. // 创建一个能写入宝藏的空箱子(写入流)
  93. const fileStream = fs.createWriteStream(filePath);
  94. headers = getHeaders(headers, "")
  95. logger.info('headers:!', headers, fileUrl);
  96. headers["User-Agent"] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
  97. const options = {
  98. headers: headers
  99. };
  100. http.get(fileUrl, options, (response) => {
  101. // 将收到的宝藏(响应流)流入箱子(文件流)中
  102. response.pipe(fileStream);
  103. // 等待宝藏完全转移完毕
  104. fileStream.on('finish', () => {
  105. // 现在宝藏已经安全地放在箱子里(文件写入完成)
  106. fileStream.close();
  107. logger.info('文件下载完成,船长!');
  108. resolve(true)
  109. });
  110. }).on('error', (err) => {
  111. // 如果在转移宝藏过程中遇到海怪(错误)...
  112. logger.error('在下载文件时遇到了问题:', err);
  113. // 别忘了关闭箱子(文件流)
  114. fileStream.close();
  115. // 如果宝藏已经损坏(文件已经部分写入),丢弃它(删除文件)
  116. if (fileStream.bytesWritten === 0) {
  117. fs.unlink(filePath, (unlinkErr) => {
  118. if (unlinkErr) logger.error('无法删除不完整的文件:', unlinkErr);
  119. });
  120. }
  121. reject(err)
  122. });
  123. });
  124. }
  125. module.exports = {
  126. request_get,
  127. request_post,
  128. dowFile
  129. };