2021-11-02 17:55:49 +08:00
using Newtonsoft.Json ;
using System ;
using System.Collections ;
using System.Collections.Generic ;
using System.Linq ;
using System.Net.Http ;
using System.Text ;
using System.Threading ;
using System.Threading.Tasks ;
using UnityEngine ;
namespace Assets.Scripts.Apis
{
public class PfHttpClientHandler : HttpClientHandler
{
protected async override Task < HttpResponseMessage > SendAsync (
HttpRequestMessage request , CancellationToken cancellationToken )
{
2021-11-23 15:58:02 +08:00
try
2021-11-02 17:55:49 +08:00
{
2021-11-23 15:58:02 +08:00
var response = await base . SendAsync ( request , cancellationToken ) . ConfigureAwait ( false ) ;
//{"result":false,"errMsg":"已在其他设备登录","code":401}
var result = await response . Content . ReadAsStringAsync ( ) . ConfigureAwait ( false ) ;
if ( request . RequestUri . ToString ( ) . Contains ( App . Host ) & & result . Contains ( @"{""result"":false," ) )
2021-11-02 17:55:49 +08:00
{
2021-11-23 15:58:02 +08:00
var json = ParseJson < JsonResult < object > > ( result ) ;
if ( json . code = = 401 )
{
App . is401 = json . errMsg ;
UnityMainThreadDispatcher . Instance ( ) . Enqueue ( LoadLogin ( json . errMsg ) ) ;
}
2021-11-02 17:55:49 +08:00
}
2021-11-23 15:58:02 +08:00
else
{
App . is401 = null ;
}
if ( response . StatusCode ! = System . Net . HttpStatusCode . OK )
{
response . Content = new StringContent ( new JsonResult < object > { result = false , errMsg = "Please check if the network connection is normal." , data = null } . ToString ( ) ) ;
}
return response ;
2021-11-02 17:55:49 +08:00
}
2021-11-23 15:58:02 +08:00
catch ( Exception e )
2021-11-02 17:55:49 +08:00
{
2021-11-23 15:58:02 +08:00
Debug . Log ( e ) ;
HttpResponseMessage httpResponse = new HttpResponseMessage
{
StatusCode = System . Net . HttpStatusCode . BadRequest ,
Content = new StringContent ( new JsonResult < object > { result = false , errMsg = "Please check if the network connection is normal." , data = null } . ToString ( ) )
} ;
return httpResponse ;
2021-11-02 17:55:49 +08:00
}
2021-11-23 15:58:02 +08:00
2021-11-02 17:55:49 +08:00
}
private T ParseJson < T > ( string result )
{
return JsonConvert . DeserializeObject < T > ( result , new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling . Local
} ) ;
}
IEnumerator LoadLogin ( string msg )
{
UnityEngine . SceneManagement . SceneManager . LoadScene ( 0 ) ;
yield return null ;
}
}
}