我们目前涉及到的现有的接收请求方式有三种,
第一种:
页面式的Form表单
第二种:
服务的webservice形式的xml
第三个:
restful风格的post包体json
第一种比较老,博客园的登录就是这样的。找了个例子
这里不做具体讨论了。
例子
List<KeyValuePair<string, string>> paramList = new List<KeyValuePair<string, string>>(); HttpClient _client = new HttpClient(); async void DownloadPageAsync() { // Use static HttpClient to avoid exhausting system resources for network connections. var result = await _client.PostAsync(new Uri(url), new FormUrlEncodedContent(paramList)); // Write status code. Console.WriteLine("STATUS CODE: " + result.StatusCode); result.EnsureSuccessStatusCode(); string resultStr = await result.Content.ReadAsStringAsync(); Console.WriteLine(resultStr); } DownloadPageAsync();
第二种的,webservice的,之前的博客里有。
第三种,比较新的json的请求方式
针对这种,就只能用json字符串来提交了,具体代码是
string url = getPRC_Url(serviceName, apiName, null); string body = "{"; //如果需要POST数据 if (!(parameters == null || parameters.Count == 0)) { StringBuilder buffer = new StringBuilder(); foreach (string key in parameters.Keys) { buffer.AppendFormat(""{0}":"{1}",", key, parameters[key]); } body += buffer.ToString() + "}"; } try { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; httpWebRequest.Timeout = 20000; byte[] btBodys = Encoding.UTF8.GetBytes(body); httpWebRequest.ContentLength = btBodys.Length; httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length); HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()); string responseContent = streamReader.ReadToEnd(); return responseContent; } catch (Exception ex) { return null; }
主要是这个入参需要放在包体里,并且得是"{}"形式的方可。