/// <summary>
/// 封装POST、GET网络请求
/// </summary>
/// <param name="url">请求的接口地址</param>
/// <param name="method">方法类型GET,POST</param>
/// <param name="json">json数据</param>
/// <param name="parm">参数</param>
/// <returns></returns>
private static string HttpComm(string url, string method, string json, string parm = "")
{
string result = string.Empty;//返回结果
try
{
if (method.ToUpper() == "GET" && parm != "")//GET请求
{
url += $"?phone={parm}";
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method.ToUpper();
request.ContentType = "application/json;charset=UTF-8";
if (method.ToUpper() == "POST")//POST请求
{
byte[] bytedata = Encoding.UTF8.GetBytes(json);
int lenght = bytedata.Length;
request.ContentLength = lenght;
Stream wirteStream = request.GetRequestStream();
wirteStream.Write(bytedata, 0, bytedata.Length);
wirteStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamResult = response.GetResponseStream();
//获取内容
using (StreamReader reader = new StreamReader(streamResult, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
}
catch (Exception e)
{
var s = e.Message;// SystemConfig.LogInfo(e.Message);
}
return result;
}
二、获取POST请求过来的数据。(于2020-03-28 更新)
/// <summary>
/// 接受用户发送的消息
/// </summary>
[HttpPost]
public string Indexs()
{
string postString = "无数据";
if (HttpContext.Request.HttpMethod.ToUpper() == "POST")
{
string xmlPath = string.Empty;
Response.ContentType = "text/plain";
using (Stream stream = HttpContext.Request.InputStream)
{
Byte[] postBytes = new Byte[stream.Length];
stream.Read(postBytes, 0, (Int32)stream.Length);
postString = Encoding.UTF8.GetString(postBytes);
if (string.IsNullOrEmpty(postString))
{
postString = "没有数据";
}
StreamWriter str = new StreamWriter(@"F:\数据打印.txt", true, Encoding.UTF8);
str.WriteLine(postString);
str.Close();
}
}
return postString;
}