代码之家  ›  专栏  ›  技术社区  ›  0fnt

获取状态代码401的响应内容

  •  0
  • 0fnt  · 技术社区  · 15 年前

    我正在尝试建立一个到服务器的连接,该服务器为我的所有请求以及正常的HTML响应发送401身份验证错误。例如 但是,我还想读取随附的HTML响应,以便分析它。使用livehttpheaders捕获的头交换示例: 显然,内容长度不是零。火狐显示它是javascript。

    https://172.31.1.251:1003/fgtauth?73e285357b2dc5cc
    Request:
    GET /fgtauth?73e285357b2dc5cc HTTP/1.1
    Host: 172.31.1.251:1003
    User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1b4) Gecko/20090423 Firefox/3.5b4 (.NET CLR 3.5.30729)
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Language: en-us,en;q=0.5
    Accept-Encoding: gzip,deflate
    Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
    Keep-Alive: 300
    Connection: keep-alive
    
    Response:
    HTTP/1.x 401 Unauthorized
    WWW-Authenticate: Fortigate
    Content-Length: 1091
    Connection: Keep-Alive
    Cache-Control: no-cache
    Content-Type: text/html
    

    此时,Firefox中会打开一个表单,要求我输入用户名和密码。

    https://172.31.1.251:1003/
    
    Request:
    POST / HTTP/1.1
    Host: 172.31.1.251:1003
    User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1b4) Gecko/20090423 Firefox/3.5b4 (.NET CLR 3.5.30729)
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Language: en-us,en;q=0.5
    Accept-Encoding: gzip,deflate
    Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
    Keep-Alive: 300
    Connection: keep-alive
    Referer: https://172.31.1.251:1003/
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 93
    magic=73e285357b2dc5cc&username=uuxx&password=xxuu&4Tredir=http%3A%2F%2Fwww.google.com%2F
    
    
    Response:
    HTTP/1.x 401 Unauthorized
    WWW-Authenticate: Fortigate
    Content-Length: 924
    Connection: Keep-Alive
    Cache-Control: no-cache
    Content-Type: text/html
    

    此时,我被重定向到另一个URL。然而,我所面临的问题是如何获得与401一起未经授权发送的lengt924的内容,因为该内容将帮助我进一步做我想做的事情。但最重要的是:

    WebResponse loginResponse = loginRequest.GetResponse();
    

    引发异常。

    如果有任何建议能帮助我了解实际内容,我将不胜感激。

    谢谢。

    1 回复  |  直到 15 年前
        1
  •  4
  •   SLaks    15 年前

    你需要阅读 WebException Response 属性,如下所示:

    WebResponse loginResponse;
    try {
        loginResponse = loginRequest.GetResponse();
    } catch(WebException ex) {
        if (ex.Status == WebExceptionStatus.ProtocolError) {
            loginResponse = ex.Response;
        } else
            throw;
    }
    
    //Do something with the response, and remember to dispose it.