string postURL ="http://xxxxx.ashx"; List<string> paramName = new List<string>(); List<string> paramValue = new List<string>(); paramName.Add("userName"); paramName.Add("password"); paramValue.Add("zhangsan"); paramValue.Add("123456"); /// <summary> /// http协议 get请求 接受返回结果 /// <para>创建作者:李勇</para> /// <para>创建日期:2014-07-31</para> /// </summary> /// <param name="url"></param> /// <param name="paramName"></param> /// <param name="paramValue"></param> /// <returns></returns> protected string GetRequest(string url, List<string> paramName, List<string> paramValue) { string result = string.Empty; try { if (paramName != null && paramValue != null) { // 编辑并Encoding提交的数据 StringBuilder sbuilder = new StringBuilder(paramName[0] + "=" + paramValue[0]); for (int i = 1; i < paramName.Count; i++) sbuilder.Append("&" + paramName[i] + "=" + paramValue[i]); url = url + "?" + sbuilder.ToString(); var tokenRequest = (HttpWebRequest)WebRequest.Create(url); using (WebResponse tokenResponse = tokenRequest.GetResponse()) { Stream stream = tokenResponse.GetResponseStream(); if (stream != null) { using (var responseReader = new System.IO.StreamReader(stream, Encoding.UTF8)) { result = responseReader.ReadToEnd(); } } } return result; } } catch (Exception ex) { if (ex == null) ex = null; } return result; } /// <summary> /// http协议 post数据 接受返回结果 /// <para>创建作者:李勇</para> /// <para>创建日期:2014-07-31</para> /// </summary> /// <param name="url"></param> /// <param name="paramName"></param> /// <param name="paramValue"></param> /// <returns></returns> protected string PostRequest(string url, List<string> paramName, List<string> paramValue) { string result = string.Empty; try { if (paramName != null && paramValue != null) { // 编辑并Encoding提交的数据 StringBuilder sbuilder = new StringBuilder(paramName[0] + "=" + paramValue[0]); for (int i = 1; i < paramName.Count; i++) sbuilder.Append("&" + paramName[i] + "=" + paramValue[i]); byte[] data = Encoding.UTF8.GetBytes(sbuilder.ToString()); // 发送请求 System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); stream.Close(); } // 获得回复 System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { result = reader.ReadToEnd(); reader.Close(); response.Close(); } } } catch (Exception ex) { } return result; }
http Get和Post请求方式,布布扣,bubuko.com
时间: 2024-10-15 13:16:00