【问题标题】:Set the Host Header when using invoke-restmethod使用 invoke-restmethod 时设置 Host Header
【发布时间】:2015-11-05 20:38:36
【问题描述】:

由于某种原因,这不起作用

Invoke-RestMethod -Uri "http://localhost" -Headers @{"Host"="web.domain.com"}

我得到了错误

The 'Host' header must be modified using the appropriate property or method

但我找不到有关如何执行此操作的方法或属性。

谢谢

【问题讨论】:

  • 你用的是什么版本的powershell?你的标签说 2.0,但我不相信 Invoke-RestMethod 是在 3.0 之前添加的。我能够在 Windows 8.1 上的 Powershell 4.0 上使用您上面提供的确切命令而不会出错。
  • 我使用的是powershell v3.0

标签: powershell powershell-3.0


【解决方案1】:

这是PowerShell version 4.0中已修复的错误:

C:\PS> (irm http://localhost -Headers @{Host='web.domain.com'}).html

xmlns                                   head                                    body
-----                                   ----                                    ----
http://www.w3.org/1999/xhtml            head                                    body

【讨论】:

  • 那么解决方法是什么?我看到了你粘贴的表格,但我不确定我真正在看什么。
  • 这只是通过显示请求返回的“HTML”来表明 OP 的命令在 PowerShell V4 中有效。在表格格式中,这只是显示 XML 命名空间 decl 以及 head 和 body 元素标签。
【解决方案2】:

为了记录,我使用 WebRequest 解决了这个问题

$bytes = [system.Text.Encoding]::UTF8.GetBytes("key=value")
$web = [net.WebRequest]::Create("http://localhost") -as [net.HttpWebRequest]
$web.ContentType = "application/x-www-form-urlencoded"
$web.Host = "web.domain.com"
$web.Method = "POST"
$web.ContentLength = $bytes.Length
$stream = $web.GetRequestStream()
$stream.Write($bytes,0,$bytes.Length)

【讨论】:

  • 您是否看到过错误“您必须在调用 [Begin]GetResponse 之前将 ContentLength 字节写入请求流”?
猜你喜欢
  • 1970-01-01
  • 2017-08-17
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多