C# POST GET

2021-03-05 19:26

阅读:649

标签: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;
}

 

封装泛型传值

///

 

/// 指定Post地址使用Get 方式获取全部字符串
///
/// 请求后台地址
///
public static string Post(string url, Dictionary 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


评论


亲,登录后才可以留言!