Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.17 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Xml;
  9. using System.Xml.Serialization;
  10.  
  11. namespace Library_Common.WebAPI
  12. {
  13.     //Шлет в какое-нибудь любое WebAPI запрос и возвращает ответ
  14.     public static class WebAPIRequester
  15.     {
  16.  
  17.         public static string GetData<T>(T operation, string requestUrlString, string authorizationString, string contentType, string acceptType)
  18.         {
  19.             return GetData(FormatPostData(operation), requestUrlString, authorizationString, contentType, acceptType);
  20.         }
  21.  
  22.         private static string GetData(string postData, string requestUrlString, string authorizationString, string contentType, string acceptType)
  23.         {
  24.             var request = (HttpWebRequest)WebRequest.Create(requestUrlString);
  25.            
  26.             var data = Encoding.UTF8.GetBytes(postData);
  27.  
  28.             request.Method = "POST";
  29.             request.PreAuthenticate = true;
  30.             request.Headers.Add("Authorization", authorizationString);            
  31.             request.ContentType = contentType;
  32.             request.Accept = acceptType;
  33.             request.ContentLength = data.Length;
  34.  
  35.             using (var stream = request.GetRequestStream())
  36.             {
  37.                 stream.Write(data, 0, data.Length);
  38.             }
  39.  
  40.             var response = (HttpWebResponse)request.GetResponse();
  41.             var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
  42.  
  43.             return responseString;
  44.         }
  45.  
  46.         private static string FormatPostData<T>(T operation)
  47.         {
  48.             var serializer = new XmlSerializer(typeof(T));
  49.             string result;
  50.             using (var sww = new StringWriter())
  51.             {
  52.                 using (var writer = XmlWriter.Create(sww))
  53.                 {
  54.                     serializer.Serialize(writer, operation, new XmlSerializerNamespaces());
  55.                     result = sww.ToString();
  56.                 }
  57.             }
  58.             return result;
  59.         }
  60.                
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement