我已经声明了一个继承自WebClient的类ClientClass。我正在使用此类来定义HttpWebRequest对象,因为我想传递SSL证书以及客户端身份验证请求。
public class ClientClass : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
request = (HttpWebRequest)base.GetWebRequest(address);
request.ClientCertificates.Add(GetCertificate());
return request;
}
private static X509Certificate2 GetCertificate()
{
string certificateThumbprint = AADHelper.DecryptConfigurationSetting(ConfigHelper.CertificateThumbprint);
string thumbprint = certificateThumbprint;
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
List<X509Certificate2> list = store.Certificates.Cast<X509Certificate2>().ToList();
X509Certificate2 clientCertificate = list.Find(c => c.Thumbprint != null && c.Thumbprint.Equals(thumbprint, StringComparison.InvariantCultureIgnoreCase));
return clientCertificate;
}
}
使用WebClient Class的UploadData方法,我可以发送POST请求并获取响应字符串。但我想收到响应头以及字符串。我想过使用HttpWebResponse进行响应,但我不确定我将如何发送帖子请求。
我发送POST请求的代码如下:
using (var client = new ClientClass())
{
client.Headers.Add("content-type", "application/json");
client.Headers.Add("x-ms-tracking-id", TrackingId.ToString());
string rawResponse;
rawResponse = Encoding.ASCII.GetString(client.UploadData(Url, "POST", Encoding.Default.GetBytes(jsonString))); dataAccessLayer.InsertKeyReplacementKFSAudit(keyReplacementID, TrackingId, jsonString, rawResponse, request.User, startTime, endTime);
}
您能否帮助我了解如何阅读回复标题。 提前谢谢。
答案 0 :(得分:0)
您可以使用client.ResponseHeaders
来检索回复标题。
try
{
rawResponse = Encoding.ASCII.GetString(client.UploadData(Url, "POST", Encoding.Default.GetBytes(jsonString)));
var responseHeaders = client.ResponseHeaders;
}
catch (WebException wex) // To handle error
{
// wex.Response.Headers // You can retrieve the headers
//((HttpWebResponse)wex.Response).StatusCode //You can handle StatusCode like this;
}