这是拨打电话的方法:
public async System.Threading.Tasks.Task<Session> GetSessionFromLoginAsync()
{
try
{
var client = CustomHttpClient.GetClient();
var httpRequest = PrepareRequest(_host, HttpMethod.Post, _connParameters);
try
{
var httpResponse = await client.SendAsync(httpRequest);
if (!httpResponse.IsSuccessStatusCode)
{
throw CustomException.CreateExceptionFromResponseErrors(httpResponse);
}
if (!httpResponse.IsSuccessStatusCode)
{
return null;
}
var headers = httpResponse.Headers.ToString();
string keyRoute = "ROUTEID=";
int posRouteID = headers.IndexOf(keyRoute);
string routeID2End = headers.Substring(posRouteID + keyRoute.Length, headers.Length - posRouteID - keyRoute.Length);
int semiColumn = routeID2End.IndexOf(";");
var routeID = ";" + keyRoute + routeID2End.Substring(0, semiColumn);
string dataResult = httpResponse.Content.ReadAsStringAsync().Result;
session = JsonConvert.DeserializeObject<SessionSL>(dataResult);
session.RouteID = routeID;
}
catch (WebException ex)
{
var stream = ex.Response.GetResponseStream();
using (var sr = new StreamReader(stream))
{
Console.WriteLine(sr.ReadToEnd());
}
}
}
catch (Exception e)
{
_esito = SendError(_esito, e, Constants.ErrorCode.LoginError);
}
return session;
}
public static HttpRequestMessage PrepareRequest(string host, HttpMethod method, object contentObj)
{
var jsonObj = JsonConvert.SerializeObject(contentObj);
ServicePointManager.ServerCertificateValidationCallback += delegate (object sender, X509Certificate cert,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{ return true; };
StringContent content = new StringContent(jsonObj.ToString(), Encoding.UTF8, "application/json");
var HttpRequest = new HttpRequestMessage()
{
RequestUri = new Uri(host),
Method = method,
Content = content
};
return HttpRequest;
}
这是CustomHttpClient类:
public sealed class CustomHttpClient
{
private static HttpClient _client;
public static HttpClient GetClient()
{
if (_client == null)
{
var messageHandler = new HttpClientHandler()
{
UseCookies = false,
};
//messageHandler.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls;
//messageHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
ServicePointManager.ServerCertificateValidationCallback += delegate (object sender, X509Certificate cert,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{ return true; };
_client = new HttpClient(messageHandler)
{
Timeout = TimeSpan.FromSeconds(Constants._HTTP_TIMEOUT_SEC),
//BaseAddress = new Uri("myendpoint");
};
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Add("Connection", "keep-alive");
}
return _client;
}
}
我的应用是世界粮食计划署... 我不明白的是,我使用Xamarin Forms制作应用程序时使用的相同方法,但从未在响应中收到错误HTTP 500 ... 而且我认为代码中没有错误..即使在服务器上也没有错误,因为使用Postman之类的工具,我可以轻松连接,并且总是收到消息“ 200 OK” ...