Guest User

Untitled

a guest
Aug 18th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. Send C# variables to PHP via POST
  2. public static string Post(string service, IDictionary<string, string> objects)
  3. {
  4. // Create a request using a URL that can receive a post.
  5. WebRequest request = WebRequest.Create(ServiceAdress+service+".php");
  6. // Set the Method property of the request to POST.
  7. request.Method = "POST";
  8. // Create POST data and convert it to a byte array.
  9.  
  10. StringBuilder b= new StringBuilder();
  11. foreach(KeyValuePair<string,string> o in objects)
  12. b.Append(HttpUtility.UrlEncode(o.Key)).Append("=").Append(HttpUtility.UrlEncode(o.Value??"")).Append("&");
  13. if (PHPSESSID != null)
  14. b.Append("PHPSESSID=").Append(PHPSESSID).Append('&');
  15.  
  16. string postData = b.ToString(0, b.Length - 1);
  17. byte[] byteArray = Encoding.UTF8.GetBytes(postData);
  18. request.ContentType = "application/x-www-form-urlencoded";
  19. request.ContentLength = byteArray.Length;
  20. Stream dataStream = request.GetRequestStream();
  21. dataStream.Write(byteArray, 0, byteArray.Length);
  22. dataStream.Close();
  23. WebResponse response = request.GetResponse();
  24.  
  25. if (((HttpWebResponse)response).StatusCode != HttpStatusCode.OK)
  26. return null;
  27.  
  28. dataStream = response.GetResponseStream();
  29. StreamReader reader = new StreamReader(dataStream);
  30. string responseFromServer = reader.ReadToEnd();
  31. Console.WriteLine(responseFromServer);
  32. reader.Close();
  33.  
  34. dataStream.Close();
  35. response.Close();
  36. return responseFromServer;
  37. }
Add Comment
Please, Sign In to add comment