首页 > 代码库 > http Get和Post请求方式
http Get和Post请求方式
string postURL ="http://xxxxx.ashx"; List<string> paramName = new List<string>(); List<string> paramValue = http://www.mamicode.com/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 =http://www.mamicode.com/ 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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。