一般我们在写 http post 的时候 都是下边这种情况
1 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); 2 3 request.Method = "POST"; 4 5 request.ContentType = "application/x-www-form-urlencoded"; 6 7 request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr); 8 9 ...(省略代码,网上有很多就不多写了)windows 8
1 private async Task<string> WebRequestPost(string uri, string requestDetails) 2 { 3 string result = string.Empty; 4 WebRequest webRequest = WebRequest.Create(uri); 5 webRequest.ContentType = "application/x-www-form-urlencoded"; 6 webRequest.Method = "POST"; 7 byte[] bytes = Encoding.UTF8.GetBytes(requestDetails); 8 using (Stream outputStream = await webRequest.GetRequestStreamAsync()) 9 { 10 outputStream.Write(bytes, 0, bytes.Length); 11 } 12 using (WebResponse webResponse = await webRequest.GetResponseAsync()) 13 { 14 StreamReader sr = new StreamReader(webResponse.GetResponseStream()); 15 result = sr.ReadToEnd(); 16 } 17 return result; 18 }
windows phone 8
1 public async Task<string> HttpRequestPost(string uri, string requestDetails) 2 { 3 string resultStr = ""; 4 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); 5 // 设定发送方式 6 request.Method = "post"; 7 request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; 8 byte[] buffer = System.Text.Encoding.UTF8.GetBytes(requestDetails); 9 // 设定内容长度 10 request.ContentLength = buffer.Length; 11 12 //将需要发送的字符数组写入请求流中 13 using (var stream = (await Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null))) 14 { 15 await stream.WriteAsync(buffer, 0, buffer.Length); 16 } 17 18 //响应读取 19 using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null))) 20 { 21 using (var responseStream = response.GetResponseStream()) 22 { 23 using (var sr = new StreamReader(responseStream)) 24 { 25 resultStr = await sr.ReadToEndAsync(); 26 } 27 } 28 response.Close(); 29 } 30 return resultStr; 31 }
第一次发表文章 不太会写 如果我有写的不对得地方 欢迎各位 大牛 多提意见 谢谢!