Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading.Tasks;
- using System.Xml;
- using System.Xml.Serialization;
- namespace Library_Common.WebAPI
- {
- //Шлет в какое-нибудь любое WebAPI запрос и возвращает ответ
- public static class WebAPIRequester
- {
- public static string GetData<T>(T operation, string requestUrlString, string authorizationString, string contentType, string acceptType)
- {
- return GetData(FormatPostData(operation), requestUrlString, authorizationString, contentType, acceptType);
- }
- private static string GetData(string postData, string requestUrlString, string authorizationString, string contentType, string acceptType)
- {
- var request = (HttpWebRequest)WebRequest.Create(requestUrlString);
- var data = Encoding.UTF8.GetBytes(postData);
- request.Method = "POST";
- request.PreAuthenticate = true;
- request.Headers.Add("Authorization", authorizationString);
- request.ContentType = contentType;
- request.Accept = acceptType;
- request.ContentLength = data.Length;
- using (var stream = request.GetRequestStream())
- {
- stream.Write(data, 0, data.Length);
- }
- var response = (HttpWebResponse)request.GetResponse();
- var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
- return responseString;
- }
- private static string FormatPostData<T>(T operation)
- {
- var serializer = new XmlSerializer(typeof(T));
- string result;
- using (var sww = new StringWriter())
- {
- using (var writer = XmlWriter.Create(sww))
- {
- serializer.Serialize(writer, operation, new XmlSerializerNamespaces());
- result = sww.ToString();
- }
- }
- return result;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement