I am trying to use ModernHttpClient to replace the HttpClient. But I noticed some issues on Android and iOS platform. Not sure if I am not using them correctly and hope I can get some help here. The below code works well with HttpClient (using HttpClientHandler instead of NativeMessageHandler)
Thanks in advance.
The issues on Android:
I found even I set AllowAutoRedirect = false when creating the http handler, it still does the autoredirect.
The issue on iOS:
it failed to retrieved the cookies using the below code even I can debug and see the cookie in the response on iOS
The code like below :
public async Task<string> Login(string EmailAddress, string Password)
{
var postData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("j_username",EmailAddress),
new KeyValuePair<string, string>("j_password", Password),
new KeyValuePair<string, string>("_spring_security_remember_me", "yes"),
new KeyValuePair<string, string>("spring-security-redirect", "")
};
HttpContent postContent = new FormUrlEncodedContent(postData);
CookieContainer cookieContainer = new CookieContainer();
try
{
using (NativeMessageHandler= new NativeMessageHandler() //using ModernHttpClient replaced Httpclient
{
CookieContainer = cookieContainer,
AllowAutoRedirect = false,
UseCookies = true
})
using (HttpClient httpClient = new HttpClient(httpHandler))
{
httpClient.DefaultRequestHeaders.Add("Accept-Language", "en-US,en;q=0.8");
httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
string LoginUrl = BaseUrl + "/j_spring_security_check_2";
var response = await httpClient.PostAsync(LoginUrl, postContent);
if (response != null && response.StatusCode == HttpStatusCode.Found) // here on Android, i always http 200 instead of http 302
{
string token = string.Empty;
var responseCookies = cookieContainer.GetCookies(new Uri(BaseUrl));// here on iOS, responseCookies always contains 0 cookies
foreach (Cookie cookie in responseCookies)
{
if (cookie.Name.Equals("grails_remember_me", StringComparison.OrdinalIgnoreCase))
{
token = cookie.Value;
}
}
return token;
}
}
}
catch (Exception ex)
{
Debug.WriteLine("PostRequestAsync exception {0}", ex.ToString());
}
return String.Empty;
}
}