Permission denied: 'C:\\Users\\ainusers\\Desktop\\request'

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

这个主要是因为你没有添加后缀,缺少文件格式,不应该是路径

f = open("C:\\Users\\ainusers\\Desktop\\request.csv","w")

如果本文帮到您了,欢迎关注本人公众号:周三想吧

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

im not using lazada api but rather trying to ping lazada mtop with reversed egineered signature to get restock iformation through the json or whatever it is something along this line. now im facing this issue PS C:\Users\micle\Desktop\Cursor projects\laz endpoint\store> python .\tracker.py 2025-12-11 07:26:07,271 INFO Loaded 100 proxies from C:\Users\micle\Desktop\Cursor projects\laz endpoint\store\proxies.txt 2025-12-11 07:26:07,271 INFO Initialized proxy manager with 100 proxies (TTL: 480s = 8.0min) 2025-12-11 07:26:07,273 WARNING Failed to load cookies (attempt 1/3): [Errno 13] Permission denied, retrying in 0.1s... 2025-12-11 07:26:07,374 WARNING Failed to load cookies (attempt 2/3): [Errno 13] Permission denied, retrying in 0.2s... 2025-12-11 07:26:07,595 WARNING Failed to load cookies from file after 3 attempts: [Errno 13] Permission denied 2025-12-11 07:26:07,597 INFO No existing cookies found, will warm up on first use 2025-12-11 07:26:07,597 INFO Product 3487788485: TEST MODE - Running WITHOUT proxy (first product) 2025-12-11 07:26:07,598 WARNING Product 3487788485: URL in config.json has no signed parameters - will extract on first poll 2025-12-11 07:26:07,598 INFO Product 3487815178: Assigned proxy http://sakongsa:sakongsa303_region-asiapacific_session-GzK1V... (1 proxy per product) 2025-12-11 07:26:07,598 WARNING Product 3487815178: URL in config.json has no signed parameters - will extract on first poll 2025-12-11 07:26:07,598 INFO Product 3487868077: Assigned proxy http://sakongsa:sakongsa303_region-asiapacific_session-GqJ5w... (1 proxy per product) 2025-12-11 07:26:07,599 WARNING Product 3487868077: URL in config.json has no signed parameters - will extract on first poll 2025-12-11 07:26:07,599 INFO Starting 3 polling threads... 2025-12-11 07:26:07,600 INFO [Product 3487788485] Starting polling thread 2025-12-11 07:26:07,600 INFO Started thread for Product 3487788485 2025-12-11 07:26:07,636 INFO [Product 3487815178] Starting polling thread 2025-12-11 07:26:07,636 INFO Started thread for Product 3487815178 2025-12-11 07:26:07,737 INFO [Product 3487868077] Starting polling thread 2025-12-11 07:26:07,737 INFO Started thread for Product 3487868077 2025-12-11 07:26:07,752 INFO All 3 polling threads started. Monitoring products concurrently... Press Ctrl+C to stop... 2025-12-11 07:26:30,228 WARNING Failed to load cookies (attempt 1/3): [Errno 13] Permission denied, retrying in 0.1s... 2025-12-11 07:26:30,329 WARNING Failed to load cookies (attempt 2/3): [Errno 13] Permission denied, retrying in 0.2s... 2025-12-11 07:26:30,531 WARNING Failed to load cookies from file after 3 attempts: [Errno 13] Permission denied 2025-12-11 07:26:30,531 INFO Making API request to https://acs-m.lazada.sg/h5/mtop.global.detail.web.getdetailinfo/1.0/?jsv=2.6.1&appKey=24677475&api=m... (has signed params: False) 2025-12-11 07:26:30,532 INFO Using browser's proxy for API request: http://sakongsa:sakongsa303_region-asiapacific_session-GqJ5w... 2025-12-11 07:26:32,845 WARNING Punish detected in API response (type: rate_limit). Response keys: ['ret', 'data', 'dialogSize'] 2025-12-11 07:26:32,845 WARNING API ret field: ['FAIL_SYS_USER_VALIDATE', 'RGV587_ERROR::SM::哎哟喂,被挤爆啦,请稍后重试'] 2025-12-11 07:26:32,845 WARNING API data keys: ['url', 'dialogSize'] 2025-12-11 07:26:32,845 WARNING URL had signed parameters: False 2025-12-11 07:26:32,846 INFO Saved punish response diagnostic to punish_response_3487868077_20251211_072632.json [WARN] Product 3487868077: fetch error (rate_limit), consecutive=1 2025-12-11 07:26:32,846 INFO Product 3487868077: Poll returned error: rate_limit 2025-12-11 07:26:32,847 WARNING Product 3487868077: Rate limited - backing off for 41.7s (base: 30s + 11.7s jitter, consecutive errors: 1) [MODE] Product 3487868077: idle → error_backoff (rate_limit (backoff 41.7s, consecutive=1)) | next poll in 41.7s 2025-12-11 07:26:32,847 INFO Product 3487868077: Mode changed idle → error_backoff (rate_limit (backoff 41.7s, consecutive=1)), interval=41.7s 2025-12-11 07:26:35,995 INFO TEST MODE: Running without proxy for this product 2025-12-11 07:26:35,996 WARNING Failed to load cookies (attempt 1/3): [Errno 13] Permission denied, retrying in 0.1s... 2025-12-11 07:26:36,098 WARNING Failed to load cookies (attempt 2/3): [Errno 13] Permission denied, retrying in 0.2s... 2025-12-11 07:26:36,300 WARNING Failed to load cookies from file after 3 attempts: [Errno 13] Permission denied 2025-12-11 07:26:36,300 INFO Making API request to https://acs-m.lazada.sg/h5/mtop.global.detail.web.getdetailinfo/1.0/?jsv=2.6.1&appKey=24677475&api=m... (has signed params: False) 2025-12-11 07:26:36,300 INFO TEST MODE: Making API request WITHOUT proxy 2025-12-11 07:26:36,454 WARNING Punish detected in API response (type: rate_limit). Response keys: ['ret', 'data', 'dialogSize'] 2025-12-11 07:26:36,454 WARNING API ret field: ['FAIL_SYS_USER_VALIDATE', 'RGV587_ERROR::SM::哎哟喂,被挤爆啦,请稍后重试'] 2025-12-11 07:26:36,455 WARNING API data keys: ['url', 'dialogSize'] 2025-12-11 07:26:36,455 WARNING URL had signed parameters: False 2025-12-11 07:26:36,456 INFO Saved punish response diagnostic to punish_response_3487788485_20251211_072636.json [WARN] Product 3487788485: fetch error (rate_limit), consecutive=1 2025-12-11 07:26:36,456 INFO Product 3487788485: Poll returned error: rate_limit 2025-12-11 07:26:36,456 WARNING Product 3487788485: Rate limited - backing off for 39.1s (base: 30s + 9.1s jitter, consecutive errors: 1) [MODE] Product 3487788485: idle → error_backoff (rate_limit (backoff 39.1s, consecutive=1)) | next poll in 39.1s 2025-12-11 07:26:36,457 INFO Product 3487788485: Mode changed idle → error_backoff (rate_limit (backoff 39.1s, consecutive=1)), interval=39.1s 2025-12-11 07:26:37,614 WARNING Failed to load cookies (attempt 1/3): [Errno 13] Permission denied, retrying in 0.1s... 2025-12-11 07:26:37,715 WARNING Failed to load cookies (attempt 2/3): [Errno 13] Permission denied, retrying in 0.2s... 2025-12-11 07:26:37,917 WARNING Failed to load cookies from file after 3 attempts: [Errno 13] Permission denied 2025-12-11 07:26:37,918 INFO Making API request to https://acs-m.lazada.sg/h5/mtop.global.detail.web.getdetailinfo/1.0/?jsv=2.6.1&appKey=24677475&api=m... (has signed params: False) 2025-12-11 07:26:37,918 INFO Using browser's proxy for API request: http://sakongsa:sakongsa303_region-asiapacific_session-GzK1V... 2025-12-11 07:26:38,807 WARNING Punish detected in API response (type: rate_limit). Response keys: ['ret', 'data', 'dialogSize'] 2025-12-11 07:26:38,807 WARNING API ret field: ['FAIL_SYS_USER_VALIDATE', 'RGV587_ERROR::SM::哎哟喂,被挤爆啦,请稍后重试'] 2025-12-11 07:26:38,807 WARNING API data keys: ['url', 'dialogSize'] 2025-12-11 07:26:38,807 WARNING URL had signed parameters: False 2025-12-11 07:26:38,809 INFO Saved punish response diagnostic to punish_response_3487815178_20251211_072638.json [WARN] Product 3487815178: fetch error (rate_limit), consecutive=1 2025-12-11 07:26:38,809 INFO Product 3487815178: Poll returned error: rate_limit 2025-12-11 07:26:38,809 WARNING Product 3487815178: Rate limited - backing off for 38.6s (base: 30s + 8.6s jitter, consecutive errors: 1) [MODE] Product 3487815178: idle → error_backoff (rate_limit (backoff 38.6s, consecutive=1)) | next poll in 38.6s 2025-12-11 07:26:38,809 INFO Product 3487815178: Mode changed idle → error_backoff (rate_limit (backoff 38.6s, consecutive=1)), interval=38.6s [SHUTDOWN] Received interrupt signal, shutting down gracefully... 2025-12-11 07:26:56,339 INFO Received interrupt signal (signal 2), shutting down... [SHUTDOWN] Waiting for threads to finish (max 5 seconds)... 2025-12-11 07:26:56,340 INFO [Product 3487868077] Polling thread stopped 2025-12-11 07:26:56,340 INFO [Product 3487815178] Polling thread stopped 2025-12-11 07:26:56,340 INFO Stop event set, waiting for threads to finish... 2025-12-11 07:26:56,340 INFO [Product 3487788485] Polling thread stopped [SHUTDOWN] Shutdown complete 2025-12-11 07:26:56,341 INFO Shutdown complete PS C:\Users\micle\Desktop\Cursor projects\laz endpoint\store>
最新发布
12-12
PS C:\Users\Administrator> <# >> .SYNOPSIS >> 基于 curl 的 PowerShell HTTP 请求工具 >> #> >> PS C:\Users\Administrator> function Invoke-CurlRequest { >> [CmdletBinding()] >> param( >> [Parameter(Mandatory = $true, Position = 0)] >> [string]$Url, >> >> [ValidateSet('GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS')] >> [string]$Method = 'GET', >> >> [hashtable]$Headers = @{}, >> >> [string]$Body, >> >> [string]$OutputFile, >> >> [ValidateSet('Text', 'Json', 'Xml', 'Object')] >> [string]$OutputType = 'Text', >> >> [int]$Timeout = 30, >> >> [int]$RetryCount = 0, >> >> [int]$RetryInterval = 5, >> >> [int[]]$RetryOnStatusCodes = @(500, 502, 503, 504), >> >> [switch]$RetryOnTimeout, >> >> [switch]$Insecure, >> >> [switch]$FollowRedirects, >> >> [switch]$VerboseOutput >> ) >> >> # 硬编码 curl 路径 >> $curlPath = "E:\curl-8.15.0_4-win64-mingw\bin\curl.exe" >> if (-not (Test-Path $curlPath)) { >> throw "curl 未找到: $curlPath" >> } >> >> # 构建 curl 参数 >> $curlArgs = @("-s", "-X", $Method, "--max-time", $Timeout) >> >> # 添加请求头 >> foreach ($key in $Headers.Keys) { >> $headerValue = $Headers[$key] >> $curlArgs += "-H" >> $curlArgs += "`"$key: $headerValue`"" >> } >> 所在位置 行:33 字符: 25 + $curlArgs += "`"$key: $headerValue`"" + ~~~~~ 变量引用无效。':' 后面的变量名称字符无效。请考虑使用 ${} 分隔名称。 所在位置 行:1 字符: 29 + function Invoke-CurlRequest { + ~ 语句块或类型定义中缺少右“}”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : InvalidVariableReferenceWithDrive PS C:\Users\Administrator> # 添加请求体 PS C:\Users\Administrator> if (-not [string]::IsNullOrEmpty($Body)) { >> $curlArgs += "-d" >> $curlArgs += $Body >> } >> PS C:\Users\Administrator> # 添加输出文件 PS C:\Users\Administrator> if (-not [string]::IsNullOrEmpty($OutputFile)) { >> $outputDir = [System.IO.Path]::GetDirectoryName($OutputFile) >> if (-not [string]::IsNullOrEmpty($outputDir) -and -not (Test-Path $outputDir)) { >> New-Item -ItemType Directory -Path $outputDir -Force | Out-Null >> } >> $curlArgs += "-o" >> $curlArgs += "`"$OutputFile`"" >> } >> PS C:\Users\Administrator> # 添加安全选项 PS C:\Users\Administrator> if ($Insecure) { >> $curlArgs += "--insecure" >> } >> PS C:\Users\Administrator> # 添加重定向选项 PS C:\Users\Administrator> if ($FollowRedirects) { >> $curlArgs += "-L" >> } >> PS C:\Users\Administrator> # URL 编码处理 PS C:\Users\Administrator> $encodedUrl = [System.Web.HttpUtility]::UrlPathEncode($Url) 找不到类型 [System.Web.HttpUtility]。 所在位置 行:1 字符: 19 + $encodedUrl = [System.Web.HttpUtility]::UrlPathEncode($Url) + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Web.HttpUtility:TypeName) [],RuntimeException + FullyQualifiedErrorId : TypeNotFound PS C:\Users\Administrator> $curlArgs += "`"$encodedUrl`"" PS C:\Users\Administrator> PS C:\Users\Administrator> # 重试逻辑 PS C:\Users\Administrator> $attempt = 0 PS C:\Users\Administrator> $maxAttempts = $RetryCount + 1 PS C:\Users\Administrator> $retriedErrors = @() PS C:\Users\Administrator> PS C:\Users\Administrator> do { >> $attempt++ >> $shouldRetry = $false >> $curlError = $null >> >> try { >> if ($VerboseOutput -or $VerbosePreference -ne 'SilentlyContinue') { >> Write-Verbose "执行 curl 命令 (尝试 $attempt/$maxAttempts):" >> Write-Verbose "$curlPath $($curlArgs -join ' ')" >> } >> >> # 执行 curl >> $result = & $curlPath $curlArgs 2>&1 >> >> # 处理输出 >> $response = @{ >> Status = "Success" >> StatusCode = 200 >> Content = $null >> Headers = @{} >> RawOutput = $result >> Attempts = $attempt >> } >> >> # 解析状态码 >> if ($result -match 'HTTP/\d\.\d (\d{3})') { >> $response.StatusCode = [int]$matches[1] >> } >> >> # 解析响应头 >> $headerLines = $result | Where-Object { $_ -match '^< ' } >> foreach ($line in $headerLines) { >> if ($line -match '^< (\w+):\s*(.+)') { >> $response.Headers[$matches[1]] = $matches[2].Trim() >> } >> } >> >> # 提取内容 >> $contentStart = $result | Select-String -Pattern '^\{|^<' | Select-Object -First 1 >> if ($null -ne $contentStart) { >> $contentIndex = [array]::IndexOf($result, $contentStart) >> $response.Content = $result[$contentIndex..($result.Count-1)] -join "`n" >> } >> >> # 处理内容类型 >> if ($OutputType -ne 'Text' -and $null -ne $response.Content) { >> switch ($OutputType) { >> 'Json' { >> try { >> $response.Content = $response.Content | ConvertFrom-Json >> } >> catch { >> $response.Status = "JsonParseError" >> $response.ErrorMessage = $_.Exception.Message >> } >> } >> 'Xml' { >> try { >> $xml = [xml]$response.Content >> $response.Content = $xml >> } >> catch { >> $response.Status = "XmlParseError" >> $response.ErrorMessage = $_.Exception.Message >> } >> } >> 'Object' { >> # 根据内容类型自动转换 >> if ($response.Headers['Content-Type'] -like '*json*') { >> try { >> $response.Content = $response.Content | ConvertFrom-Json >> } >> catch { >> $response.Status = "JsonParseError" >> $response.ErrorMessage = $_.Exception.Message >> } >> } >> elseif ($response.Headers['Content-Type'] -like '*xml*') { >> try { >> $xml = [xml]$response.Content >> $response.Content = $xml >> } >> catch { >> $response.Status = "XmlParseError" >> $response.ErrorMessage = $_.Exception.Message >> } >> } >> } >> } >> } >> >> # 检查是否需要重试 >> if ($attempt -lt $maxAttempts) { >> if ($RetryOnStatusCodes -contains $response.StatusCode) { >> $shouldRetry = $true >> $retriedErrors += "HTTP $($response.StatusCode)" >> } >> elseif ($RetryOnTimeout -and $result -match 'Operation timed out') { >> $shouldRetry = $true >> $retriedErrors += "Timeout" >> } >> } >> >> return $response >> } >> catch { >> $curlError = $_ >> $shouldRetry = ($attempt -lt $maxAttempts) -and ($RetryOnTimeout -or $RetryOnStatusCodes.Count -gt 0) >> $retriedErrors += $_.Exception.Message >> >> if (-not $shouldRetry) { >> throw $curlError >> } >> } >> >> # 指数退避 + 随机抖动 >> if ($shouldRetry) { >> $waitTime = $RetryInterval * [math]::Pow(2, $attempt - 1) >> $jitter = Get-Random -Minimum 0.1 -Maximum ($waitTime * 0.3) >> $totalWait = [math]::Ceiling($waitTime + $jitter) >> >> Write-Verbose "请求失败,将在 ${totalWait} 秒后重试 (错误: $($curlError.Exception.Message))" >> Start-Sleep -Seconds $totalWait >> } >> } while ($shouldRetry) >> } >> 所在位置 行:114 字符: 1 + } + ~ 表达式或语句中包含意外的标记“}”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken PS C:\Users\Administrator> Export-ModuleMember -Function Invoke-CurlRequest Export-ModuleMember : 只能从模块内调用 Export-ModuleMember cmdlet。 所在位置 行:1 字符: 1 + Export-ModuleMember -Function Invoke-CurlRequest + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Export-ModuleMember], InvalidOperationException + FullyQualifiedErrorId : Modules_CanOnlyExecuteExportModuleMemberInsideAModule,Microsoft.PowerShell.Commands.Expo rtModuleMemberCommand PS C:\Users\Administrator> PS C:\Users\Administrator> <# >> .SYNOPSIS >> 基于 curl 的 PowerShell HTTP 请求工具 >> #> >> PS C:\Users\Administrator> function Invoke-CurlRequest { >> [CmdletBinding()] >> param( >> [Parameter(Mandatory = $true, Position = 0)] >> [string]$Url, >> >> [ValidateSet('GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS')] >> [string]$Method = 'GET', >> >> [hashtable]$Headers = @{}, >> >> [string]$Body, >> >> [string]$OutputFile, >> >> [ValidateSet('Text', 'Json', 'Xml', 'Object')] >> [string]$OutputType = 'Text', >> >> [int]$Timeout = 30, >> >> [int]$RetryCount = 0, >> >> [int]$RetryInterval = 5, >> >> [int[]]$RetryOnStatusCodes = @(500, 502, 503, 504), >> >> [switch]$RetryOnTimeout, >> >> [switch]$Insecure, >> >> [switch]$FollowRedirects, >> >> [switch]$VerboseOutput >> ) >> >> # 硬编码 curl 路径 >> $curlPath = "E:\curl-8.15.0_4-win64-mingw\bin\curl.exe" >> if (-not (Test-Path $curlPath)) { >> throw "curl 未找到: $curlPath" >> } >> >> # 构建 curl 参数 >> $curlArgs = @("-s", "-X", $Method, "--max-time", $Timeout) >> >> # 添加请求头 >> foreach ($key in $Headers.Keys) { >> $headerValue = $Headers[$key] >> $curlArgs += "-H" >> $curlArgs += "`"$key: $headerValue`"" >> } >> 所在位置 行:33 字符: 25 + $curlArgs += "`"$key: $headerValue`"" + ~~~~~ 变量引用无效。':' 后面的变量名称字符无效。请考虑使用 ${} 分隔名称。 所在位置 行:1 字符: 29 + function Invoke-CurlRequest { + ~ 语句块或类型定义中缺少右“}”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : InvalidVariableReferenceWithDrive PS C:\Users\Administrator> # 添加请求体 PS C:\Users\Administrator> if (-not [string]::IsNullOrEmpty($Body)) { >> $curlArgs += "-d" >> $curlArgs += $Body >> } >> PS C:\Users\Administrator> # 添加输出文件 PS C:\Users\Administrator> if (-not [string]::IsNullOrEmpty($OutputFile)) { >> $outputDir = [System.IO.Path]::GetDirectoryName($OutputFile) >> if (-not [string]::IsNullOrEmpty($outputDir) -and -not (Test-Path $outputDir)) { >> New-Item -ItemType Directory -Path $outputDir -Force | Out-Null >> } >> $curlArgs += "-o" >> $curlArgs += "`"$OutputFile`"" >> } >> PS C:\Users\Administrator> # 添加安全选项 PS C:\Users\Administrator> if ($Insecure) { >> $curlArgs += "--insecure" >> } >> PS C:\Users\Administrator> # 添加重定向选项 PS C:\Users\Administrator> if ($FollowRedirects) { >> $curlArgs += "-L" >> } >> PS C:\Users\Administrator> # URL 编码处理 PS C:\Users\Administrator> $encodedUrl = [System.Web.HttpUtility]::UrlPathEncode($Url) 找不到类型 [System.Web.HttpUtility]。 所在位置 行:1 字符: 19 + $encodedUrl = [System.Web.HttpUtility]::UrlPathEncode($Url) + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Web.HttpUtility:TypeName) [],RuntimeException + FullyQualifiedErrorId : TypeNotFound PS C:\Users\Administrator> $curlArgs += "`"$encodedUrl`"" PS C:\Users\Administrator> PS C:\Users\Administrator> # 重试逻辑 PS C:\Users\Administrator> $attempt = 0 PS C:\Users\Administrator> $maxAttempts = $RetryCount + 1 PS C:\Users\Administrator> $retriedErrors = @() PS C:\Users\Administrator> PS C:\Users\Administrator> do { >> $attempt++ >> $shouldRetry = $false >> $curlError = $null >> >> try { >> if ($VerboseOutput -or $VerbosePreference -ne 'SilentlyContinue') { >> Write-Verbose "执行 curl 命令 (尝试 $attempt/$maxAttempts):" >> Write-Verbose "$curlPath $($curlArgs -join ' ')" >> } >> >> # 执行 curl >> $result = & $curlPath $curlArgs 2>&1 >> >> # 处理输出 >> $response = @{ >> Status = "Success" >> StatusCode = 200 >> Content = $null >> Headers = @{} >> RawOutput = $result >> Attempts = $attempt >> } >> >> # 解析状态码 >> if ($result -match 'HTTP/\d\.\d (\d{3})') { >> $response.StatusCode = [int]$matches[1] >> } >> >> # 解析响应头 >> $headerLines = $result | Where-Object { $_ -match '^< ' } >> foreach ($line in $headerLines) { >> if ($line -match '^< (\w+):\s*(.+)') { >> $response.Headers[$matches[1]] = $matches[2].Trim() >> } >> } >> >> # 提取内容 >> $contentStart = $result | Select-String -Pattern '^\{|^<' | Select-Object -First 1 >> if ($null -ne $contentStart) { >> $contentIndex = [array]::IndexOf($result, $contentStart) >> $response.Content = $result[$contentIndex..($result.Count-1)] -join "`n" >> } >> >> # 处理内容类型 >> if ($OutputType -ne 'Text' -and $null -ne $response.Content) { >> switch ($OutputType) { >> 'Json' { >> try { >> $response.Content = $response.Content | ConvertFrom-Json >> } >> catch { >> $response.Status = "JsonParseError" >> $response.ErrorMessage = $_.Exception.Message >> } >> } >> 'Xml' { >> try { >> $xml = [xml]$response.Content >> $response.Content = $xml >> } >> catch { >> $response.Status = "XmlParseError" >> $response.ErrorMessage = $_.Exception.Message >> } >> } >> 'Object' { >> # 根据内容类型自动转换 >> if ($response.Headers['Content-Type'] -like '*json*') { >> try { >> $response.Content = $response.Content | ConvertFrom-Json >> } >> catch { >> $response.Status = "JsonParseError" >> $response.ErrorMessage = $_.Exception.Message >> } >> } >> elseif ($response.Headers['Content-Type'] -like '*xml*') { >> try { >> $xml = [xml]$response.Content >> $response.Content = $xml >> } >> catch { >> $response.Status = "XmlParseError" >> $response.ErrorMessage = $_.Exception.Message >> } >> } >> } >> } >> } >> >> # 检查是否需要重试 >> if ($attempt -lt $maxAttempts) { >> if ($RetryOnStatusCodes -contains $response.StatusCode) { >> $shouldRetry = $true >> $retriedErrors += "HTTP $($response.StatusCode)" >> } >> elseif ($RetryOnTimeout -and $result -match 'Operation timed out') { >> $shouldRetry = $true >> $retriedErrors += "Timeout" >> } >> } >> >> return $response >> } >> catch { >> $curlError = $_ >> $shouldRetry = ($attempt -lt $maxAttempts) -and ($RetryOnTimeout -or $RetryOnStatusCodes.Count -gt 0) >> $retriedErrors += $_.Exception.Message >> >> if (-not $shouldRetry) { >> throw $curlError >> } >> } >> >> # 指数退避 + 随机抖动 >> if ($shouldRetry) { >> $waitTime = $RetryInterval * [math]::Pow(2, $attempt - 1) >> $jitter = Get-Random -Minimum 0.1 -Maximum ($waitTime * 0.3) >> $totalWait = [math]::Ceiling($waitTime + $jitter) >> >> Write-Verbose "请求失败,将在 ${totalWait} 秒后重试 (错误: $($curlError.Exception.Message))" >> Start-Sleep -Seconds $totalWait >> } >> } while ($shouldRetry) >> } >> 所在位置 行:114 字符: 1 + } + ~ 表达式或语句中包含意外的标记“}”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken PS C:\Users\Administrator> Export-ModuleMember -Function Invoke-CurlRequest Export-ModuleMember : 只能从模块内调用 Export-ModuleMember cmdlet。 所在位置 行:1 字符: 1 + Export-ModuleMember -Function Invoke-CurlRequest + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Export-ModuleMember], InvalidOperationException + FullyQualifiedErrorId : Modules_CanOnlyExecuteExportModuleMemberInsideAModule,Microsoft.PowerShell.Commands.Expo rtModuleMemberCommand PS C:\Users\Administrator> # 1. 创建模块目录 PS C:\Users\Administrator> $modulePath = "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\CurlTools" PS C:\Users\Administrator> New-Item -ItemType Directory -Path $modulePath -Force | Out-Null PS C:\Users\Administrator> PS C:\Users\Administrator> # 2. 保存模块文件 PS C:\Users\Administrator> $psm1Content = @' >> <上面完整的CurlTools.psm1内容> >> '@ >> $psm1Content | Out-File -FilePath "$modulePath\CurlTools.psm1" -Encoding UTF8 >> PS C:\Users\Administrator> $psd1Content = @' >> <上面完整的CurlTools.psd1内容> >> '@ >> $psd1Content | Out-File -FilePath "$modulePath\CurlTools.psd1" -Encoding UTF8 >> PS C:\Users\Administrator> # 3. 绕过执行策略导入模块 PS C:\Users\Administrator> $importScript = { >> # 临时设置执行策略 >> $currentPolicy = Get-ExecutionPolicy -Scope Process -ErrorAction SilentlyContinue >> Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force -ErrorAction SilentlyContinue >> >> # 导入模块 >> Import-Module "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\CurlTools" -Force >> >> # 测试功能 >> try { >> $testResponse = Invoke-CurlRequest -Url "https://example.com" -VerboseOutput >> if ($testResponse) { >> Write-Host "✅ 模块安装成功! 测试响应状态码: $($testResponse.StatusCode)" -ForegroundColor Green >> } >> else { >> Write-Host "❌ 模块安装失败,请检查错误信息" -ForegroundColor Red >> } >> } >> catch { >> Write-Host "❌ 测试请求失败: $_" -ForegroundColor Red >> } >> >> # 恢复原始执行策略 >> Set-ExecutionPolicy -ExecutionPolicy $currentPolicy -Scope Process -Force -ErrorAction SilentlyContinue >> } >> PS C:\Users\Administrator> # 在新会话中执行 PS C:\Users\Administrator> Start-Process powershell -ArgumentList "-NoExit -Command & {$importScript}" -Verb RunAs PS C:\Users\Administrator> # 将上面的安装脚本保存到文件 PS C:\Users\Administrator> $installScript = @' >> <上面完整的Install-CurlTools.ps1内容> >> '@ >> $installScript | Out-File -FilePath "$env:TEMP\Install-CurlTools.ps1" -Encoding UTF8 >> # 使用Bypass策略运行安装脚本 >> Start-Process powershell -ArgumentList "-ExecutionPolicy Bypass -File `"$env:TEMP\Install-CurlTools.ps1`"" -Verb RunAs -Wait >> # 使用Bypass策略运行安装脚本 >> Start-Process powershell -ArgumentList "-ExecutionPolicy Bypass -File `"$env:TEMP\Install-CurlTools.ps1`"" -Verb RunAs -Wait >> # 在新终端中测试 >> Import-Module CurlTools -Force >> $response = Invoke-CurlRequest -Url "https://jsonplaceholder.typicode.com/posts/1" -OutputType Json >> $response.Content >> # 创建模块目录 >> $modulePath = "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\CurlTools" >> New-Item -ItemType Directory -Path $modulePath -Force | Out-Null >> Import-Module : 无法处理模块清单“C:\Users\Administrator\Documents\WindowsPowerShell\Modules\CurlTools\CurlTools.psd1” ,因为它不是有效的 Windows PowerShell 受限语言文件。请删除受限语言禁止使用的元素: 所在位置 C:\Users\Administrator\Documents\WindowsPowerShell\Modules\CurlTools\CurlTools.psd1:1 字符: 1 + <上面完整的CurlTools.psd1内容> + ~~~~~~~~~~~~~~~~~~~~~~~ 不允许在受限语言模式或 Data 节中使用命令“<”。 所在位置 行:10 字符: 1 + Import-Module CurlTools -Force + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (C:\Users\Admini...\CurlTools.psd1:String) [Import-Module], Missing MemberException + FullyQualifiedErrorId : Modules_InvalidManifest,Microsoft.PowerShell.Commands.ImportModuleCommand Invoke-CurlRequest : 在模块“CurlTools”中找到“Invoke-CurlRequest”命令,但无法加载该模块。有关详细信息,请运行“Import-Module CurlTools”。 所在位置 行:11 字符: 13 + $response = Invoke-CurlRequest -Url "https://jsonplaceholder.typicode ... + ~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Invoke-CurlRequest:String) [], CommandNotFoundException + FullyQualifiedErrorId : CouldNotAutoloadMatchingModule PS C:\Users\Administrator> # 创建模块文件 PS C:\Users\Administrator> @' >> <上面完整的CurlTools.psm1内容> >> '@ | Out-File -FilePath "$modulePath\CurlTools.psm1" -Encoding UTF8 >> PS C:\Users\Administrator> @' >> <上面完整的CurlTools.psd1内容> >> '@ | Out-File -FilePath "$modulePath\CurlTools.psd1" -Encoding UTF8 >> PS C:\Users\Administrator> # 临时导入模块 PS C:\Users\Administrator> Set-ExecutionPolicy Bypass -Scope Process -Force Set-ExecutionPolicy : 在模块“Microsoft.PowerShell.Security”中找到“Set-ExecutionPolicy”命令,但无法加载该模块。有关详细信息,请运行“Import-Module Mi crosoft.PowerShell.Security”。 所在位置 行:1 字符: 1 + Set-ExecutionPolicy Bypass -Scope Process -Force + ~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Set-ExecutionPolicy:String) [], CommandNotFoundException + FullyQualifiedErrorId : CouldNotAutoloadMatchingModule PS C:\Users\Administrator> Import-Module CurlTools -Force Import-Module : 无法处理模块清单“C:\Users\Administrator\Documents\WindowsPowerShell\Modules\CurlTools\CurlTools.psd1” ,因为它不是有效的 Windows PowerShell 受限语言文件。请删除受限语言禁止使用的元素: 所在位置 C:\Users\Administrator\Documents\WindowsPowerShell\Modules\CurlTools\CurlTools.psd1:1 字符: 1 + <上面完整的CurlTools.psd1内容> + ~~~~~~~~~~~~~~~~~~~~~~~ 不允许在受限语言模式或 Data 节中使用命令“<”。 所在位置 行:1 字符: 1 + Import-Module CurlTools -Force + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (C:\Users\Admini...\CurlTools.psd1:String) [Import-Module], Missing MemberException + FullyQualifiedErrorId : Modules_InvalidManifest,Microsoft.PowerShell.Commands.ImportModuleCommand PS C:\Users\Administrator> PS C:\Users\Administrator> # 测试请求 PS C:\Users\Administrator> Invoke-CurlRequest -Url "https://jsonplaceholder.typicode.com/posts/1" -OutputType Json Invoke-CurlRequest : 在模块“CurlTools”中找到“Invoke-CurlRequest”命令,但无法加载该模块。有关详细信息,请运行“Import-Module CurlTools”。 所在位置 行:1 字符: 1 + Invoke-CurlRequest -Url "https://jsonplaceholder.typicode.com/posts/1 ... + ~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Invoke-CurlRequest:String) [], CommandNotFoundException + FullyQualifiedErrorId : CouldNotAutoloadMatchingModule PS C:\Users\Administrator>
08-17
PS C:\Users\Administrator> # 确保加载必要的 .NET 程序集 PS C:\Users\Administrator> try { >> # 尝试加载 System.Net.Http 程序集 >> Add-Type -AssemblyName System.Net.Http -ErrorAction Stop >> >> # 验证关键类型是否可用 >> if (-not ("System.Net.Http.HttpRequestMessage" -as [type])) { >> throw "关键类型加载失败" >> } >> } >> catch { >> Write-Warning "System.Net.Http 程序集加载失败: $($_.Exception.Message)" >> >> # 修复方法 1:重新注册 .NET Framework >> Write-Host "正在重新注册 .NET Framework..." -ForegroundColor Yellow >> Start-Process "C:\Windows\Microsoft.NET\Framework\v4.0.30319\ngen.exe" "update" -Wait -NoNewWindow >> >> # 修复方法 2:手动加载程序集 >> $httpDllPath = "C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Net.Http.dll" >> >> if (Test-Path $httpDllPath) { >> Write-Host "手动加载程序集: $httpDllPath" -ForegroundColor Yellow >> Add-Type -Path $httpDllPath >> } >> else { >> Write-Error "关键文件缺失: $httpDllPath" >> Write-Host "请安装 .NET Framework 4.8: https://dotnet.microsoft.com/download/dotnet-framework/net48" -ForegroundColor Red >> } >> } >> PS C:\Users\Administrator> # 验证修复 PS C:\Users\Administrator> if ("System.Net.Http.HttpRequestMessage" -as [type]) { >> Write-Host "✅ .NET HTTP 程序集加载成功" -ForegroundColor Green >> } >> else { >> Write-Error "❌ .NET HTTP 程序集加载失败,需要重启或重新安装.NET" >> } >> ✅ .NET HTTP 程序集加载成功 PS C:\Users\Administrator> function Invoke-EnhancedCurlRequest { >> <# >> .SYNOPSIS >> 增强版 HTTP 请求函数,兼容不同 .NET 环境 >> #> >> param( >> [Parameter(Mandatory=$true)] >> [string]$Uri, >> >> [ValidateSet('GET','POST','PUT','DELETE')] >> [string]$Method = 'GET', >> >> [hashtable]$Headers = @{}, >> >> [object]$Body, >> >> [int]$Timeout = 30 >> ) >> >> # 尝试使用 HttpClient(.NET 4.5+) >> if ("System.Net.Http.HttpClient" -as [type]) { >> try { >> $request = [System.Net.Http.HttpRequestMessage]::new() >> $request.Method = $Method >> $request.RequestUri = [Uri]::new($Uri) >> >> # 添加请求头 >> foreach ($key in $Headers.Keys) { >> $request.Headers.Add($key, $Headers[$key]) >> } >> >> # 处理请求体 >> if ($Body) { >> if ($Body -is [hashtable] -or $Body -is [pscustomobject]) { >> $jsonBody = $Body | ConvertTo-Json >> $request.Content = [System.Net.Http.StringContent]::new( >> $jsonBody, >> [System.Text.Encoding]::UTF8, >> 'application/json' >> ) >> } else { >> $request.Content = [System.Net.Http.StringContent]::new( >> $Body.ToString(), >> [System.Text.Encoding]::UTF8 >> ) >> } >> } >> >> # 发送请求 >> $handler = [System.Net.Http.HttpClientHandler]::new() >> $client = [System.Net.Http.HttpClient]::new($handler) >> $client.Timeout = [System.TimeSpan]::FromSeconds($Timeout) >> >> try { >> $response = $client.SendAsync($request).GetAwaiter().GetResult() >> >> return [PSCustomObject]@{ >> StatusCode = $response.StatusCode >> Headers = $response.Headers >> Content = $response.Content.ReadAsStringAsync().Result >> IsSuccess = $response.IsSuccessStatusCode >> Technology = "HttpClient" >> } >> } finally { >> $request.Dispose() >> $client.Dispose() >> } >> } catch { >> Write-Warning "HttpClient 请求失败: $($_.Exception.Message)" >> } >> } >> >> # 回退到 WebRequest(兼容旧版 .NET) >> try { >> Write-Warning "使用 WebRequest 回退方案" >> $request = [System.Net.WebRequest]::Create($Uri) >> $request.Method = $Method >> $request.Timeout = $Timeout * 1000 >> >> # 添加请求头 >> foreach ($key in $Headers.Keys) { >> $request.Headers.Add($key, $Headers[$key]) >> } >> >> # 处理请求体 >> if ($Body) { >> $bytes = [System.Text.Encoding]::UTF8.GetBytes( >> ($Body | ConvertTo-Json) >> ) >> $request.ContentLength = $bytes.Length >> $stream = $request.GetRequestStream() >> $stream.Write($bytes, 0, $bytes.Length) >> $stream.Close() >> } >> >> # 获取响应 >> $response = $request.GetResponse() >> $reader = New-Object System.IO.StreamReader($response.GetResponseStream()) >> $content = $reader.ReadToEnd() >> >> return [PSCustomObject]@{ >> StatusCode = [int]$response.StatusCode >> Headers = $response.Headers >> Content = $content >> IsSuccess = ([int]$response.StatusCode -ge 200 -and [int]$response.StatusCode -lt 300) >> Technology = "WebRequest" >> } >> } catch [System.Net.WebException] { >> $response = $_.Exception.Response >> $reader = New-Object System.IO.StreamReader($response.GetResponseStream()) >> $content = $reader.ReadToEnd() >> >> return [PSCustomObject]@{ >> StatusCode = [int]$response.StatusCode >> Headers = $response.Headers >> Content = $content >> IsSuccess = $false >> Technology = "WebRequest" >> } >> } catch { >> Write-Error "WebRequest 请求失败: $($_.Exception.Message)" >> throw >> } >> } >> PS C:\Users\Administrator> Export-ModuleMember -Function Invoke-EnhancedCurlRequest Export-ModuleMember : 只能从模块内调用 Export-ModuleMember cmdlet。 所在位置 行:1 字符: 1 + Export-ModuleMember -Function Invoke-EnhancedCurlRequest + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Export-ModuleMember], InvalidOperationException + FullyQualifiedErrorId : Modules_CanOnlyExecuteExportModuleMemberInsideAModule,Microsoft.PowerShell.Commands.Expo rtModuleMemberCommand PS C:\Users\Administrator> PS C:\Users\Administrator> # 更新模块文件 PS C:\Users\Administrator> $moduleDir = "$env:ProgramFiles\WindowsPowerShell\Modules\PSHttpClient" PS C:\Users\Administrator> $moduleContent = @' >> # 添加程序集加载代码 >> try { >> Add-Type -AssemblyName System.Net.Http -ErrorAction Stop >> } >> catch { >> Write-Warning "无法加载System.Net.Http程序集: $($_.Exception.Message)" >> } >> >> # 这里插入上面的增强型函数代码 >> '@ -replace '<插入点>', (Get-Command Invoke-EnhancedCurlRequest -ErrorAction Stop).ScriptBlock >> PS C:\Users\Administrator> $moduleContent | Out-File "$moduleDir\PSHttpClient.psm1" -Encoding UTF8 -Force PS C:\Users\Administrator> PS C:\Users\Administrator> # 更新模块清单 PS C:\Users\Administrator> $manifestContent = @' >> @{ >> ModuleVersion = '1.1' >> RootModule = 'PSHttpClient.psm1' >> FunctionsToExport = @('Invoke-EnhancedCurlRequest') >> CompatiblePSEditions = @('Desktop', 'Core') >> PowerShellVersion = '5.1' >> } >> '@ >> $manifestContent | Out-File "$moduleDir\PSHttpClient.psd1" -Encoding UTF8 -Force >> PS C:\Users\Administrator> # 重新加载模块 PS C:\Users\Administrator> Remove-Module PSHttpClient -ErrorAction SilentlyContinue PS C:\Users\Administrator> Import-Module PSHttpClient -Force PS C:\Users\Administrator> PS C:\Users\Administrator> # 测试请求 PS C:\Users\Administrator> $testResult = Invoke-EnhancedCurlRequest -Uri "https://httpbin.org/get" -Method GET PS C:\Users\Administrator> PS C:\Users\Administrator> if ($testResult.IsSuccess) { >> Write-Host "✅ 请求成功 (使用 $($testResult.Technology)): $($testResult.StatusCode)" -ForegroundColor Green >> $testResult.Content | ConvertFrom-Json | Select-Object url, headers >> } else { >> Write-Error "❌ 请求失败: $($testResult.StatusCode)" >> $testResult.Content >> } >> ✅ 请求成功 (使用 HttpClient): OK url headers --- ------- https://httpbin.org/get @{Host=httpbin.org; X-Amzn-Trace-Id=Root=1-68a03c44-2aef25a4684787fe56e98054} PS C:\Users\Administrator>
08-17
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值