锐腾搅拌上料功能
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

125 lines
4.6 KiB

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
namespace ICSSoft.Frame.APP.Helper
{
public class WebHelper
{
public static T HttpPost<T>(string url, string body, string tocken = null)
{
T t;
try
{
Encoding encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
request.ContentType = "application/json; charset=utf-8";
if (tocken != null)
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + tocken);
byte[] buffer = encoding.GetBytes(body);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
{
t= JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
}
return t;
}
catch (WebException webEx)
{
if (webEx.Response != null)
{
using (var errorResponse = (HttpWebResponse)webEx.Response)
{
using (Stream errorDataStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(errorDataStream);
string errorResponseContent = reader.ReadToEnd();
try
{
t = JsonConvert.DeserializeObject<T>(errorResponseContent);
}
catch (Exception ex)
{
throw new Exception(webEx.InnerException.Message);
}
return t;
}
}
}
else
{
throw new Exception(webEx.Message);
}
}
}
public static T HttpGet<T>(string url, string tocken = null)
{
T t;
try
{
Encoding encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
request.ContentType = "application/json; charset=utf-8";
if (tocken != null)
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + tocken);
var res = request.GetResponse();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
{
t = JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
}
return t;
}
catch (WebException webEx)
{
if (webEx.Response != null)
{
using (var errorResponse = (HttpWebResponse)webEx.Response)
{
using (Stream errorDataStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(errorDataStream);
string errorResponseContent = reader.ReadToEnd();
try
{
t = JsonConvert.DeserializeObject<T>(errorResponseContent);
}
catch (Exception ex)
{
throw new Exception(webEx.InnerException.Message);
}
return t;
}
}
}
else
{
throw new Exception(webEx.Message);
}
}
}
}
}