引用新浪天气预报http://community.youkuaiyun.com/

本文介绍了一种使用C#从新浪天气网站抓取天气信息的方法。通过创建HTTP请求并设置必要的参数,文章详细展示了如何获取指定网页的内容,进一步解析HTML以提取具体的天气信息。

private void Page_Load(object sender, System.EventArgs e)
 {
  HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://weather.sina.com.cn/iframe/weather/210201_w.html");
  request.Method = "Get";
  request.ContentType = "application/x-www-form-urlencoded";
  WebResponse response = request.GetResponse();
  Stream s = response.GetResponseStream();
  StreamReader sr = new StreamReader(s,System.Text.Encoding.GetEncoding("GB2312"));
  string html = sr.ReadToEnd();
  s.Close();
  sr.Close();

  int start = html.IndexOf("<br>");
  html = html.Substring(start + 4);

  int end = html.IndexOf("</td>");
  html = html.Substring(0,end);

  htmResult = html;

}

PS C:\Windows\system32> iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1')) Exception calling "DownloadString" with "1" argument(s): "The underlying connection was closed: An unexpected error occ urred on a send." At line:1 char:1 + iex ((New-Object System.Net.WebClient).DownloadString('https://commun ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : WebException PS C:\Windows\system32> # 临时允许脚本执行(仅限当前进程) PS C:\Windows\system32> Set-ExecutionPolicy Bypass -Scope Process -Force PS C:\Windows\system32> [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1')) WARNING: Files from a previous installation of Chocolatey were found at 'C:\ProgramData\chocolatey'. WARNING: An existing Chocolatey installation was detected. Installation will not continue. This script will not overwrite existing installations. If there is no Chocolatey installation at '', delete the folder and attempt the installation again. Please use choco upgrade chocolatey to handle upgrades of Chocolatey itself. If the existing installation is not functional or a prior installation did not complete, follow these steps: - Backup the files at the path listed above so you can restore your previous installation if needed. - Remove the existing installation manually. - Rerun this installation script. - Reinstall any packages previously installed, if needed (refer to the lib folder in the backup). Once installation is completed, the backup folder is no longer needed and can be deleted. PS C:\Windows\system32> # 检查服务器支持的协议 PS C:\Windows\system32> $url = "https://community.chocolatey.org" PS C:\Windows\system32> [System.Net.ServicePointManager]::FindServicePoint($url).Address AbsolutePath : / AbsoluteUri : https://community.chocolatey.org/ LocalPath : / Authority : community.chocolatey.org HostNameType : Dns IsDefaultPort : True IsFile : False IsLoopback : False PathAndQuery : / Segments : {/} IsUnc : False Host : community.chocolatey.org Port : 443 Query : Fragment : Scheme : https OriginalString : https://community.chocolatey.org DnsSafeHost : community.chocolatey.org IdnHost : community.chocolatey.org IsAbsoluteUri : True UserEscaped : False UserInfo : PS C:\Windows\system32> # 检查系统代理设置 PS C:\Windows\system32> [System.Net.WebRequest]::GetSystemWebProxy().GetProxy($url) AbsolutePath : / AbsoluteUri : https://community.chocolatey.org/ LocalPath : / Authority : community.chocolatey.org HostNameType : Dns IsDefaultPort : True IsFile : False IsLoopback : False PathAndQuery : / Segments : {/} IsUnc : False Host : community.chocolatey.org Port : 443 Query : Fragment : Scheme : https OriginalString : https://community.chocolatey.org DnsSafeHost : community.chocolatey.org IdnHost : community.chocolatey.org IsAbsoluteUri : True UserEscaped : False UserInfo :
最新发布
09-22
<think> 我们当前要解决的问题有两个: 1. 在PowerShell中使用WebClient下载Chocolatey安装脚本时出现连接错误:'The underlying connection was closed: An unexpected error occurred on a send.' 2. 检测到已有Chocolatey安装,导致无法继续安装。 根据之前的信息,我们已经尝试过设置SecurityProtocol为3072(即Tls12)并绕过执行策略,但仍然出现连接错误。同时,网络测试(Test-NetConnection)显示443端口是通的,因此问题可能不在网络连通性上,而是协议协商或安全设置问题。 另外,当检测到已有Chocolatey安装时,安装脚本会停止执行。因此,我们需要分别解决这两个问题。 解决方案: 一、解决连接错误: 1. 尝试更明确地设置SecurityProtocol为Tls12(3072的数值对应Tls12,但有时需要明确指定为枚举值) 但是用户已经设置了3072,所以我们需要考虑其他可能性。 2. 考虑使用更现代的Invoke-WebRequest代替WebClient,因为Invoke-WebRequest在PowerShell 3.0及以上版本中默认使用TLS1.2(但实际行为可能受系统影响)。 3. 检查系统支持的协议:有些旧系统(如Windows 7/Server 2008 R2及更早版本)默认不支持TLS1.2,需要安装补丁。但用户正在使用Windows 10/11或Server 2016+,则通常支持。 4. 可能的原因还包括系统安全协议被组策略限制,或者存在中间人攻击拦截(如企业防火墙解密HTTPS流量),需要配置信任代理。 5. 另外,考虑使用BITS(Background Intelligent Transfer Service)来下载,因为BITS对代理和证书的处理可能不同。 二、检测到已有Chocolatey安装: 1. 如果已经安装过Chocolatey,再次运行安装脚本会提示并退出。因此,我们需要先检查是否已安装,如果已安装则不需要再次安装,或者可以尝试升级。 2. 如果用户确实想重新安装,需要先卸载现有Chocolatey。 具体步骤: 步骤一:解决连接错误(尝试多种方法) 方法1:使用Invoke-WebRequest替代WebClient(如果PowerShell版本>=3.0) 注意:Invoke-WebRequest在早期PowerShell版本中可能也有同样的协议问题,所以仍需设置SecurityProtocol。 方法2:尝试设置多个安全协议(Tls12, Tls11, Tls)以增加兼容性(尽管服务器可能只接受Tls12,但客户端设置多个不影响) 方法3:使用BITS传输 方法4:手动下载脚本并执行 步骤二:处理已有安装 检查Chocolatey是否已安装: - 通过命令 `choco -v` 检查 - 或者检查环境变量中是否有Chocolatey的路径 如果已安装,则可以选择: - 升级:`choco upgrade chocolatey` - 卸载:`choco uninstall chocolatey`(然后重新安装) 具体操作步骤: 针对连接错误,我们依次尝试以下命令: 1. 设置安全协议并尝试使用Invoke-WebRequest: ```powershell [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 Set-ExecutionPolicy Bypass -Scope Process -Force Invoke-WebRequest 'https://community.chocolatey.org/install.ps1' -UseBasicParsing | Invoke-Expression ``` 2. 如果上述方法失败,尝试使用WebClient并设置多个协议(包括Tls12和Tls11): ```powershell [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 -bor [System.Net.SecurityProtocolType]::Tls11 Set-ExecutionPolicy Bypass -Scope Process -Force iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1')) ``` 3. 如果还是失败,尝试使用BITS(需要系统支持): ```powershell [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 Set-ExecutionPolicy Bypass -Scope Process -Force $script = Start-BitsTransfer -Source 'https://community.chocolatey.org/install.ps1' -Asynchronous # 等待下载完成 $download = $script | Complete-BitsTransfer $scriptContent = Get-Content -Path $download.FileName -Raw Invoke-Expression $scriptContent ``` 4. 手动下载并执行(推荐,因为稳定): ```powershell [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 $url = "https://community.chocolatey.org/install.ps1" $output = "$env:TEMP\chocolatey-install.ps1" (New-Object System.Net.WebClient).DownloadFile($url, $output) Set-ExecutionPolicy Bypass -Scope Process -Force & $output ``` 针对已有安装: 在运行安装脚本之前,先检查是否已安装Chocolatey: 在PowerShell中执行: ```powershell # 检查Chocolatey是否已安装 if (Get-Command choco -ErrorAction SilentlyContinue) { Write-Host "Chocolatey is already installed. Version: $(choco -v)" # 可以选择升级 choco upgrade chocolatey -y } else { # 安装过程 # 这里放置上述下载并安装的命令 } ``` 或者,如果用户希望强制重新安装,则先卸载: ```powershell # 卸载现有Chocolatey if (Get-Command choco -ErrorAction SilentlyContinue) { # 卸载命令 choco uninstall chocolatey -y # 等待卸载完成,可能需要手动删除残留的环境变量和文件夹 # 默认安装路径:$env:ProgramData\chocolatey Remove-Item -Recurse -Force "$env:ProgramData\chocolatey" -ErrorAction SilentlyContinue # 从环境变量PATH中移除Chocolatey的路径(如果有) $oldPath = [Environment]::GetEnvironmentVariable('Path', [EnvironmentVariableTarget]::Machine) -replace [System.Text.RegularExpressions.Regex]::Escape("$env:ProgramData\chocolatey\bin") + '(?>;)?', '' [Environment]::SetEnvironmentVariable('Path', $oldPath, [EnvironmentVariableTarget]::Machine) $env:Path = ($env:Path -split ';' | Where-Object { $_ -notlike "$env:ProgramData\chocolatey\bin*" }) -join ';' } ``` 然后重新安装。 注意:卸载操作可能会影响其他通过Chocolatey安装的软件,因此通常建议升级而不是卸载。 综合解决方案: 由于用户已经尝试过安装并出现连接错误,且可能已经存在安装,我们可以按以下步骤: 步骤1:检查是否已安装Chocolatey,如果已安装则升级并退出安装过程。 步骤2:如果未安装,则尝试多种下载方法安装。 我们编写一个综合脚本: ```powershell # 设置协议和策略 [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 Set-ExecutionPolicy Bypass -Scope Process -Force -ErrorAction SilentlyContinue # 检查是否已安装Chocolatey try { $chocoVersion = choco -v if ($chocoVersion) { Write-Host "Chocolatey is already installed (version $chocoVersion). Upgrading..." choco upgrade chocolatey -y exit 0 } } catch { # 未安装 } # 尝试安装 try { # 方法1:使用Invoke-WebRequest Write-Host "Trying to install Chocolatey using Invoke-WebRequest..." Invoke-WebRequest 'https://community.chocolatey.org/install.ps1' -UseBasicParsing | Invoke-Expression } catch { Write-Host "Method 1 failed: $($_.Exception.Message)" try { # 方法2:使用WebClient Write-Host "Trying to install Chocolatey using WebClient..." iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1')) } catch { Write-Host "Method 2 failed: $($_.Exception.Message)" try { # 方法3:手动下载 Write-Host "Trying to install Chocolatey by downloading manually..." $url = "https://community.chocolatey.org/install.ps1" $installScript = Join-Path $env:TEMP "chocolatey-install.ps1" (New-Object System.Net.WebClient).DownloadFile($url, $installScript) & $installScript } catch { Write-Host "All methods failed. Please check your network and try again." exit 1 } } } ``` 注意:在生产环境中,建议使用最稳定的手动下载方法。 重要:如果用户处于企业代理后面,可能需要配置WebClient或Invoke-WebRequest的代理设置,例如: ```powershell $webClient = New-Object System.Net.WebClient $webClient.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials ``` 或者设置系统级的代理环境变量: $env:HTTP_PROXY="http://proxy:port" $env:HTTPS_PROXY="http://proxy:port" 总结:首先确保协议设置正确,然后尝试多种下载方法;同时处理已安装的情况。 相关问题: 1. 如何验证Chocolatey安装是否成功? 2. 在企业代理环境下如何安装Chocolatey? 3. 如何彻底卸载Chocolatey及其所有安装的软件包? 4. 升级Chocolatey后需要哪些后续操作? </think> ### 解决 Chocolatey 安装问题:连接错误与已有安装冲突 #### 一、解决连接错误:"The underlying connection was closed" **根本原因**:安全协议不匹配(服务器要求 TLS 1.2+,客户端使用旧协议)[^3] ```powershell # 解决方案 1:强制使用 TLS 1.2(推荐) [System.Net.ServicePointManager]::SecurityProtocol = 'Tls12' iex (Invoke-WebRequest -Uri 'https://community.chocolatey.org/install.ps1' -UseBasicParsing).Content # 解决方案 2:兼容旧系统(Windows Server 2012 R2 等) [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 -bor [System.Net.SecurityProtocolType]::Tls11 iex (New-Object Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1') ``` > **验证协议支持**: > ```powershell > $url = "https://community.chocolatey.org" > [Net.ServicePointManager]::FindServicePoint($url).Address > ``` > 输出应包含 `SslProtocols.Tls12`[^1] #### 二、解决已有安装冲突 **当检测到 Chocolatey 已安装时:** ```powershell # 步骤 1:检查现有版本 choco -v # 若命令存在即已安装 # 步骤 2:卸载旧版本(需管理员权限) choco uninstall chocolatey -y Remove-Item -Recurse -Force "$env:ProgramData\chocolatey" -ErrorAction SilentlyContinue # 步骤 3:清理环境变量(关键!) [Environment]::SetEnvironmentVariable("PATH", [Environment]::GetEnvironmentVariable("PATH", "Machine") -replace "C:\\ProgramData\\chocolatey\\bin;?", ""), "Machine") ``` #### 三、完整安装流程 ```powershell # 步骤 1:开启 TLS 1.2 [Net.ServicePointManager]::SecurityProtocol = 'Tls12' # 步骤 2:跳过执行策略限制 Set-ExecutionPolicy Bypass -Scope Process -Force # 步骤 3:卸载旧版本(如有) if (Get-Command choco -ErrorAction SilentlyContinue) { choco uninstall chocolatey -y Remove-Item -Recurse -Force "$env:ProgramData\chocolatey" } # 步骤 4:安装新版本(使用更稳定的 Invoke-WebRequest) Invoke-WebRequest https://community.chocolatey.org/install.ps1 -UseBasicParsing | Invoke-Expression # 步骤 5:验证安装 choco list -l # 应显示已安装包列表 ``` #### 四、企业环境特殊处理 **若遇代理拦截**: ```powershell # 设置代理凭证 $proxy = New-Object System.Net.WebProxy("http://proxy-server:8080") $proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials [System.Net.WebRequest]::DefaultWebProxy = $proxy # 手动下载安装 (New-Object Net.WebClient).DownloadFile( 'https://community.chocolatey.org/install.ps1', "$env:TEMP\choco-install.ps1" ) & "$env:TEMP\choco-install.ps1" ``` > **关键提示**: > Windows Server 2012 R2 等旧系统需安装 [KB3140245](https://support.microsoft.com/en-us/topic/update-to-enable-tls-1-1-and-tls-1-2-as-default-secure-protocols-in-winhttp-in-windows-c4bd73d2-31d7-761e-0178-11268bb10392) 补丁支持 TLS 1.2[^2]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值