Guest User

Untitled

a guest
Jan 17th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. var jsonString = JsonConvert.SerializeObject(post_parameters);
  2. var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
  3.  
  4. public class MyFormUrlEncodedContent : ByteArrayContent
  5. {
  6. public MyFormUrlEncodedContent(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
  7. : base(MyFormUrlEncodedContent.GetContentByteArray(nameValueCollection))
  8. {
  9. base.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
  10. }
  11. private static byte[] GetContentByteArray(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
  12. {
  13. if (nameValueCollection == null)
  14. {
  15. throw new ArgumentNullException("nameValueCollection");
  16. }
  17. StringBuilder stringBuilder = new StringBuilder();
  18. foreach (KeyValuePair<string, string> current in nameValueCollection)
  19. {
  20. if (stringBuilder.Length > 0)
  21. {
  22. stringBuilder.Append('&');
  23. }
  24.  
  25. stringBuilder.Append(MyFormUrlEncodedContent.Encode(current.Key));
  26. stringBuilder.Append('=');
  27. stringBuilder.Append(MyFormUrlEncodedContent.Encode(current.Value));
  28. }
  29. return Encoding.Default.GetBytes(stringBuilder.ToString());
  30. }
  31. private static string Encode(string data)
  32. {
  33. if (string.IsNullOrEmpty(data))
  34. {
  35. return string.Empty;
  36. }
  37. return System.Net.WebUtility.UrlEncode(data).Replace("%20", "+");
  38. }
  39. }
  40.  
  41. void sendDocument()
  42. {
  43. string url = "www.mysite.com/page.php";
  44. StringBuilder postData = new StringBuilder();
  45. postData.Append(String.Format("{0}={1}&", HttpUtility.HtmlEncode("prop"), HttpUtility.HtmlEncode("value")));
  46. postData.Append(String.Format("{0}={1}", HttpUtility.HtmlEncode("prop2"), HttpUtility.HtmlEncode("value2")));
  47. StringContent myStringContent = new StringContent(postData.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded");
  48. HttpClient client = new HttpClient();
  49. HttpResponseMessage message = client.PostAsync(url, myStringContent).GetAwaiter().GetResult();
  50. string responseContent = message.Content.ReadAsStringAsync().GetAwaiter().GetResult();
  51. }
Add Comment
Please, Sign In to add comment