- Без одноэлементного шаблона
- С одноэлементным шаблоном
Вот мой код
Код: Выделить всё
public HttpClient GetConnection()
{
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(baseAddress);
httpClient.Timeout = System.TimeSpan.FromMilliseconds(timeout);
return httpClient;
}
Код: Выделить всё
public async Task PostAsync(String url, TRequest requestData)
{
HttpClient client = GetConnection();
String responseData = null;
if (client != null)
{
String serializedObject = await Task.Run(() => JsonConvert.SerializeObject(requestData, _jsonSerializerSettings));
var jsonContent = new StringContent(serializedObject, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(new Uri(url, UriKind.Relative), jsonContent);
responseData = await HandleResponse(response);
return await Task.Run(() => JsonConvert.DeserializeObject(responseData, _jsonSerializerSettings));
}
else
{
throw new NullReferenceException("NullReferenceException @ PostAsync httpclient is null WebRequest.cs");
}
}
Код: Выделить всё
new LoginService(new WebRequest()).UserLogin(userRequest);
Код: Выделить всё
_webRequest.PostAsync(Constants.USER_LOGIN, userRequest);
здесь мой одноэлементный класс также является потокобезопасным.
Код: Выделить всё
private static readonly Lazy lazy =
new Lazy(() => new HttpService());
public static HttpService Instance { get { return lazy.Value; } }
private HttpClient getConnection()
{
client = new HttpClient();
client.Timeout = System.TimeSpan.FromMilliseconds(timeout);
//client.MaxResponseContentBufferSize = 500000;
client.BaseAddress = new Uri(baseAddress);
return client;
}
Код: Выделить всё
public Task sendData(String url,String jsonData)
{
var jsonContent = new StringContent(jsonData, System.Text.Encoding.UTF8, "application/json");
return getConnection().PostAsync(new Uri(url, UriKind.Relative), jsonContent);
}
Код: Выделить всё
HttpService.Instance.sendData(...)
Подробнее здесь: https://stackoverflow.com/questions/487 ... nt-request
Мобильная версия