private static byte[] GetContentByteArray(IEnumerable <KeyValuePair <string, string> > nameValueCollection) { StringBuilder stringBuilder = new StringBuilder(); foreach (KeyValuePair <string, string> current in nameValueCollection) { if (stringBuilder.Length > 0) { stringBuilder.Append('&'); } stringBuilder.Append(MyFormUrlEncodedContent.Encode(current.Key)); stringBuilder.Append('='); stringBuilder.Append(MyFormUrlEncodedContent.Encode(current.Value)); } return(Encoding.Default.GetBytes(stringBuilder.ToString())); }
// 执行post操作 public static String doPost(HttpClient client, String url, Dictionary <String, String> parameters, int timeOutInMillisecond) { HttpContent content = new MyFormUrlEncodedContent(parameters); Task <HttpResponseMessage> task = client.PostAsync(url, content); if (task.Wait(timeOutInMillisecond)) { HttpResponseMessage response = task.Result; if (response.StatusCode == HttpStatusCode.OK) { Task <string> result = response.Content.ReadAsStringAsync(); result.Wait(); return(result.Result); } } return(null); }
public MyFormUrlEncodedContent(IEnumerable <KeyValuePair <string, string> > nameValueCollection) : base(MyFormUrlEncodedContent.GetContentByteArray(nameValueCollection)) { base.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded"); }