向服务器发出请求时,我随机收到超时异常。我一直在尝试 httpwebrequest、restsharp 和 httpclient。我不能使用HttpClient
,因为我需要添加自定义证书并且它们没有实现。
这是我到目前为止发现的:
-requests 在控制台应用程序中工作正常
-requests 在 http url 中工作正常
- 请求不适用于带有 X-CSRF-Token 和 X-FORMS_BASED_AUTH_ACCEPTED 的客户端证书 (.pfx) 的 https(它似乎适用于 NTLM)
-在每次调用(不是 cookie)时仅使用 NTLM 身份验证时,请求似乎工作正常
初始化 RestClient:
Setup.RestClient = new RestClient(App.EnvironmentServerUrl);
Setup.RestClient.ClientCertificates = new X509CertificateCollection() { Setup.Certificate };
Setup.RestClient.CookieContainer = new CookieContainer();
if (!String.IsNullOrEmpty(App.Cookie.Value))
Setup.RestClient.CookieContainer.Add(new Uri(App.EnvironmentServerUrl), App.Cookie);
Setup.RestClient.AddHandler("application/json", NewtonsoftJsonSerializer.Default);
Setup.RestClient.AddHandler("text/json", NewtonsoftJsonSerializer.Default);
Setup.RestClient.AddHandler("text/x-json", NewtonsoftJsonSerializer.Default);
Setup.RestClient.AddHandler("text/javascript", NewtonsoftJsonSerializer.Default);
Setup.RestClient.AddHandler("*+json", NewtonsoftJsonSerializer.Default);
拨打电话:
var request = new RestRequest(url, Method.POST);
request.OnBeforeDeserialization = resp =>
{
string byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (resp.Content != null && resp.Content.Length > 0 && resp.Content.StartsWith(byteOrderMarkUtf8))
resp.Content = resp.Content.Remove(0, byteOrderMarkUtf8.Length);
};
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", this.SerializeToJson(parameters), ParameterType.RequestBody);
request.JsonSerializer = NewtonsoftJsonSerializer.Default;
request.AddHeader("X-CSRF-Token", "Fetch");
request.AddHeader("X-FORMS_BASED_AUTH_ACCEPTED", "f");
if (App.Cookie == null || String.IsNullOrEmpty(App.Cookie.Value))
{
CredentialCache credentials = new CredentialCache();
credentials.Add(new Uri(App.EnvironmentServerUrl), "NTLM", new NetworkCredential(App.Credentials.UserName, App.Credentials.Password));
request.Credentials = credentials;
}
return await this.ExecuteAsync<T>(request);
public Task<T> ExecuteAsync<T>(RestRequest request) where T : new()
{
var taskCompletionSource = new TaskCompletionSource<T>();
Setup.RestClient.ExecuteAsync<T>(request, (response) => {
if (App.Cookie == null || String.IsNullOrEmpty(App.Cookie.Value))
{
App.Cookie = Setup.RestClient.CookieContainer.GetCookies(Setup.RestClient.BaseUrl)["FedAuth"];
}
if (!this.IsSuccessStatusCode(response.StatusCode))
{
taskCompletionSource.SetException(response.ErrorException);
}
else
{
taskCompletionSource.SetResult(response.Data);
}
});
return taskCompletionSource.Task;
注意:我已经设法实现了自己的 AndroidClientHandler 以使用客户端证书,但我遇到了 NTLM 身份验证错误。