我正在使用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文档成功授权后,API会使用访问x令牌进行响应,而我不确定如何访问或从HTTP标头中捕获它。
我可以知道一个很好的方法吗?
答案 0 :(得分:4)
这比我想象的更容易。
string xtoken= response.Headers["custom-header"];
Console.WriteLine(xtoken);
答案 1 :(得分:4)
尝试如下所示,使用WebRequest类表示请求数据。在大多数情况下,WebRequest类足以接收数据。但是,如果需要设置特定于协议的属性,则必须将WebRequest强制转换为特定于协议的类型。例如,要访问HttpWebRequest的HTTP特定属性,请将WebRequest强制转换为HttpWebRequest引用。
{{1}}