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!
text 2.10 KB | None | 0 0
  1. class WebAPIRequester
  2. {
  3. public WebAPIRequester() { }
  4. private string requestUrlString;
  5. private string authorizationString;
  6. private string contentType;
  7. private string acceptType;
  8.  
  9.  
  10. public void Connect(string requestUrlString, string authorizationString, string contentType, string acceptType)
  11. {
  12. this.requestUrlString = requestUrlString;
  13. this.authorizationString = authorizationString;
  14. this.contentType = contentType;
  15. this.acceptType = acceptType;
  16. }
  17.  
  18. public string GetData(string postData)
  19. {
  20. var request = (HttpWebRequest)WebRequest.Create(requestUrlString);
  21.  
  22. var data = Encoding.UTF8.GetBytes(postData);
  23.  
  24. request.Method = "POST";
  25. request.PreAuthenticate = true;
  26. request.Headers.Add("Authorization", this.authorizationString);
  27. request.ContentType = this.contentType;
  28. request.Accept = this.acceptType;
  29. request.ContentLength = data.Length;
  30.  
  31. using (var stream = request.GetRequestStream())
  32. {
  33. stream.Write(data, 0, data.Length);
  34. }
  35.  
  36. var response = (HttpWebResponse)request.GetResponse();
  37. var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
  38.  
  39. return responseString;
  40. }
  41.  
  42. public string GetData<T>(T operation)
  43. {
  44. return GetData(FormatPostData(operation));
  45. }
  46.  
  47. private string FormatPostData<T>(T operation)
  48. {
  49. var serializer = new XmlSerializer(typeof(T));
  50. string result;
  51. using (var sww = new StringWriter())
  52. {
  53. using (var writer = XmlWriter.Create(sww))
  54. {
  55. serializer.Serialize(writer, operation, new XmlSerializerNamespaces());
  56. result = sww.ToString();
  57. }
  58. }
  59. return result;
  60. }
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement