2024-10-17 10:30:13
建议这样试试看:
亲测可用,主要还是Url的拼接,这个需要客户给出格式
/// <summary>
/// 与客户WMS系统通讯获取数据
/// </summary>
/// <param name="url">接口,需要拼接成客户规定的格式</param>
/// <param name="data">请求数据,需要拼接成客户规定的Json格式</param>
/// <returns>全部数据</returns>
public string Post(string url, string data)
{
try
{
//创建请求
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//设置请求方法
request.Method = "Post";
request.Referer = "";
//将数据转换为UTF8字节流
byte[] bytes = Encoding.UTF8.GetBytes(data);
//设置发送的字节数
request.ContentLength = bytes.Length;
//设置发送内容格式
request.ContentType = "application/json; charset=UTF-8";
//获取用于写入请求数据的流对象
Stream stream = request.GetRequestStream();
//向当前流写入数据,发送请求
stream.Write(bytes, 0, bytes.Length);
//接收返回流,通过Web访问对象获取响应内容
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//通过响应内容流创建StreamReader对象
//StreamReader sr = new StreamReader(request.GetRequestStream(), Encoding.UTF8);//写错,导致一直读取不了数据
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
//读取所有内容
string retString = sr.ReadToEnd();
//关闭流
sr.Close();
stream.Close();
if (response != null)
{
//关闭响应流
response.Close();
}
if (request != null)
{
//取消请求
request.Abort();
}
return retString;
}
catch (Exception ex)
{
throw ex;
}
}
}