如何在请求后捕获由 REST API 发送的响应令牌?

How to capture a response token sent by a REST API after a request?

我正在使用 REST API,我正在使用基本身份验证,其中密码按如下方式编码为 Base64

 private XmlDocument sendXMLRequest(string requestXml)
    {
        string destinationUrl = "https://serviceapi.testgroup.com/testtp/query";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
        request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("API_TEST_NR:Testnol1$"));
        byte[] bytes;
        bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
        request.Method = "POST";

        request.ContentLength = bytes.Length;
        //request.Connection = "keep-alive";
        request.ContentType = "text/xml";
        request.KeepAlive = true;
        request.Timeout = 2000;
        request.MediaType = "text/xml";
        Stream requestStream = request.GetRequestStream();
        requestStream.Write(bytes, 0, bytes.Length);
        requestStream.Close();
        HttpWebResponse response;
        Stream responseStream;

        using (response = (HttpWebResponse)request.GetResponse())
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                responseStream = response.GetResponseStream();
                XmlReader reader = new XmlTextReader(responseStream);

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(reader);


                try { reader.Close(); }
                catch { }
                try { responseStream.Close(); }
                catch { }
                try { response.Close(); }
                catch { }
                return xmlDoc;
            }
        }
        try { response.Close(); }
        catch { }
        return null;
    } 

我是 Web Api 的新手,我知道 API 在基于 [=21] 成功授权后以访问权限 x-token 响应=] 文档,我不确定如何从 HTTP headers.

访问或捕获它

请问有什么好的方法可以实现吗?

这比我想象的用它的名字捕获要容易。

string xtoken= response.Headers["custom-header"];
Console.WriteLine(xtoken);

尝试如下,表示,使用WebRequest Class.In 请求数据大多数情况下,WebRequest class 足以接收数据。但是,如果您需要设置特定于协议的属性,则必须将 WebRequest 转换为特定于协议的类型。例如,要访问 HttpWebRequest 的 HTTP 特定属性,请将 WebRequest 转换为 HttpWebRequest 引用。

private XmlDocument GetRootLevelServiceDocument(
string serviceEndPoint, string oAuthToken)
{
XmlDocument xmlDoc = new XmlDocument();
HttpWebRequest request = CreateHttpRequest(serviceEndPoint, 
    oAuthToken);

using (HttpWebResponse response = 
    (HttpWebResponse)request.GetResponse())
{
    using (XmlReader reader = 
        XmlReader.Create(response.GetResponseStream(), 
        new XmlReaderSettings() { CloseInput = true }))
    {
        xmlDoc.Load(reader);

        string data = ReadResponse(response);
        if (response.StatusCode != HttpStatusCode.OK)
        {
            LogMsg(string.Format("Error: {0}", data));
            LogMsg(string.Format(
                "Unexpected status code returned: {0}", 
                response.StatusCode));
        }
    }
}

return xmlDoc;
}