码迷,mamicode.com
首页 > Windows程序 > 详细

C# POST GET

时间:2020-05-15 09:58:40      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:request   ade   字符串   coding   param   content   ++   命名空间   new   

//引入命名空间
//using System.Net;
//using System.IO;
public string Post(string url, string msg)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/json";

byte[] data = Encoding.UTF8.GetBytes(msg);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}

HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
{
result = sr.ReadToEnd();
}
return result;
}


public string Get(string url)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";
req.ContentType = "application/json";

HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
{
result = sr.ReadToEnd();
}
return result;
}

 

封装泛型传值

/// <summary> 

/// 指定Post地址使用Get 方式获取全部字符串
/// </summary>
/// <param name="url">请求后台地址</param>
/// <returns></returns>
public static string Post(string url, Dictionary<string, string> dic)
{
try
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/json";
#region 添加Post 参数
StringBuilder builder = new StringBuilder();
//int i = 0;
foreach (var item in dic)
{
builder.Append("\"" + item.Key + "\":\"" + item.Value + "\",");
//if (i > 0)
// builder.Append("&");
//builder.AppendFormat("{0}={1}", item.Key, item.Value);
//i++;
}
builder = new StringBuilder("{" + builder.ToString().Trim(‘,‘) + "}");
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
#endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
catch (Exception)
{
return "";
}

}

C# POST GET

标签:request   ade   字符串   coding   param   content   ++   命名空间   new   

原文地址:https://www.cnblogs.com/liangyuwen/p/12892673.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!