Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Text;
- using System.Threading.Tasks;
- using Windows.UI.Popups;
- namespace API
- {
- public class APIRequestService
- {
- private const string baseUrl = "http://mysite.com/api/";
- static HttpClient client;
- static string token;
- static APIRequestService()
- {
- client = new HttpClient();
- client.MaxResponseContentBufferSize = 25600000;
- //Тут нужно достать токен (*тут достаётся не по-замариновски)
- Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
- if (localSettings.Values.ContainsKey("access_token"))
- {
- token = localSettings.Values["access_token"].ToString();
- }
- client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
- }
- public static async Task<T> Request<T>(string urlRequest, object parameters = null)
- {
- var url = new Uri(baseUrl + urlRequest);
- HttpResponseMessage response = null;
- if (parameters != null)
- {
- var json = JsonConvert.SerializeObject(parameters);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- if (!string.IsNullOrEmpty(token))
- {
- content.Headers.Add("token", token);
- }
- try
- {
- response = await client.PostAsync(url, content);
- }
- catch (Exception ex)
- {
- //Ошыбка
- }
- }
- else
- {
- try
- {
- response = await client.GetAsync(url);
- }
- catch (Exception ex)
- {
- //Ошыбка
- }
- }
- if (response?.IsSuccessStatusCode)
- {
- if (response.Content != null)
- {
- var stringResponse = await response.Content.ReadAsStringAsync();
- var jsonResponse = JToken.Parse(jS);
- try
- {
- T objResponse = jsonResponse.ToObject<T>();
- return objResponse;
- }
- catch(Exception ex)
- {
- //Ошыбка
- }
- }
- }
- else
- {
- //Ошыбка
- }
- return default(T);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement