代码之家  ›  专栏  ›  技术社区  ›  halr9000

如何在PowerShell中获取数字HTTP状态代码

  •  19
  • halr9000  · 技术社区  · 16 年前

    我知道一个 few good ways 要在PowerShell中生成Web客户端,.NET类System.NET.WebClient和System.NET.httpWebRequest,或COM对象msxml2.xmlhttp。据我所知,唯一允许您访问数字状态代码(如200404)的是最后一个COM对象。我的问题是,我不喜欢它的工作方式,也不喜欢依赖COM对象。我还知道,由于安全漏洞等原因,微软有时会决定终止COM对象(ActiveX终止位)。

    我还缺少其他.NET方法吗?这两个对象中是否有状态代码,我只是不知道如何获取它?

    4 回复  |  直到 9 年前
        1
  •  53
  •   DarcyThomas    9 年前

    使用X0N和Joshua Ewer的答案,用一个代码示例来做一个完整的循环,我希望这不是太糟糕的形式:

    $url = 'http://google.com'
    $req = [system.Net.WebRequest]::Create($url)
    
    try {
        $res = $req.GetResponse()
    } 
    catch [System.Net.WebException] {
        $res = $_.Exception.Response
    }
    
    $res.StatusCode
    #OK
    
    [int]$res.StatusCode
    #200
    
        2
  •  12
  •   Liam Joshua    13 年前

    使用 [system.net.httpstatuscode] 枚举类型。

    ps> [enum]::getnames([system.net.httpstatuscode])
    Continue
    SwitchingProtocols
    OK
    Created
    Accepted
    NonAuthoritativeInformation
    NoContent
    ResetContent
    ...
    

    要获取数字代码,请强制转换为[int]:

    ps> [int][system.net.httpstatuscode]::ok
    200
    

    希望这有帮助,

    -奥辛

        3
  •  4
  •   joshua.ewer    16 年前

    我知道这个问题的标题是关于PowerShell的,但不是真正的问题是什么?无论哪种方式…

    webclient是一个非常简单的httpwebrequest包装器。如果您只是简单地使用服务或发布一点XML,WebClient是很好的,但是需要权衡的是,它并不像您希望的那样灵活。您将无法从WebClient获取所需信息。

    如果需要状态代码,请从httpwebresponse获取它。如果您正在使用webclient执行类似的操作(只是将字符串发布到URL):

    var bytes = 
        System.Text.Encoding.ASCII.GetBytes("my xml"); 
    
    var response = 
        new WebClient().UploadData("http://webservice.com", "POST", bytes);
    

    然后用httpwebrequest来获取状态代码。同样的想法,只是更多的选项(因此更多的代码)。

    //create a stream from whatever you want to post here
    var bytes = 
      System.Text.Encoding.ASCII.GetBytes("my xml"); 
    var request = 
      (HttpWebRequest)WebRequest.Create("http://webservice.com");
    
    //set up your request options here (method, mime-type, length)
    
    //write something to the request stream
    var requestStream = request.GetRequestStream();
    requestStream.Write(bytes, 0, bytes.Length);        
    requestStream.Close();
    
    var response = (HttpWebResponse)request.GetResponse();
    
    //returns back the HttpStatusCode enumeration
    var httpStatusCode = response.StatusCode;
    
        4
  •  1
  •   CommonToast    9 年前

    很容易

    $wc = New-Object NET.WebClient
    $wc.DownloadString($url)
    $wc.ResponseHeaders.Item("status")
    

    您可以在ResponseHeaders属性中找到其他可用的响应头(如Content-Type、Content-Length、X-Powered-By等),并通过item()方法检索它们中的任何一个。

    …但是正如罗布下面提到的,不幸的是,状态属性在这里不可用。

    推荐文章