private static string Post(string url, string jsonArgs, string token, bool isUploadPdf = false, byte[] bt = null)
{
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Authorization", token);
byte[] bytes;
if (isUploadPdf)
{
bytes = bt;
}
else
{
bytes = Encoding.UTF8.GetBytes(jsonArgs);
}
httpWebRequest.ContentLength = bytes.Length;
using (Stream stream = httpWebRequest.GetRequestStream())
{
stream.Write(bytes, 0, bytes.Length);
stream.Close();
}
httpWebRequest.Timeout = 5000;
string result = Request(httpWebRequest);
return result;
}
catch (WebException ex)
{
HttpWebResponse res = (HttpWebResponse)ex.Response;
Stream myResponseStream = res.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
return ex.ToString();
}
}
private static string Get(string url)
{
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "GET";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Timeout = 5000;
string result = Request(httpWebRequest);
return result;
}
catch (Exception ex)
{
return ex.ToString();
}
}
private static string Request(WebRequest webRequest)
{
using (var response = webRequest.GetResponse())
using (var stream = response.GetResponseStream())
using (StreamReader streamReader = new StreamReader(stream, Encoding.UTF8))
{
string result = streamReader.ReadToEnd();
return result;
}
}
C# 调用 Post Get接口
最新推荐文章于 2024-08-27 09:31:30 发布