Last active
May 23, 2020 02:12
-
-
Save BytesCrafter/2871d45c8e464e691775879e54f50725 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Net.Http; | |
using System.Net.Http.Headers; | |
using System.Collections.Generic; | |
using System.Threading.Tasks; | |
using Newtonsoft.Json; | |
namespace BytesCrafter.Xamarin | |
{ | |
public class User | |
{ | |
public string uname = string.Empty; | |
public string pword = string.Empty; | |
} | |
public class Token | |
{ | |
public string snid = string.Empty; | |
} | |
public class RestClient | |
{ | |
HttpClient client; | |
string restUrl = string.Empty; //https://www.example.com/api + /user/auth | |
public RestClient(string rootUrl) | |
{ | |
restUrl = rootUrl; | |
client = new HttpClient(); | |
client.MaxResponseContentBufferSize = 256000; | |
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); | |
} | |
public async Task<Token> SignIn(User user) | |
{ | |
var postData = new List<KeyValuePair<string, string>>(); | |
postData.Add(new KeyValuePair<string, string>("UN", user.uname)); | |
postData.Add(new KeyValuePair<string, string>("PW", user.pword)); | |
var content = new FormUrlEncodedContent(postData); | |
var response = await PostResponse<Token>(content); | |
//More checking about the response and request here. | |
return response; | |
} | |
public async Task<T> PostResponse<T>(FormUrlEncodedContent content) where T : class | |
{ | |
var response = await client.PostAsync(restUrl, content); | |
var result = response.Content.ReadAsStringAsync().Result; | |
var token = JsonConvert.DeserializeObject<T>(result); | |
//Try catch if result is an actual json. | |
return token; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment