|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- using Newtonsoft.Json.Linq;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading.Tasks;
- using System.Web;
- using Newtonsoft.Json;
- using HBLConsole.Service;
-
- namespace HBLConsole.Service
- {
- public class APIHelper
- {
-
- private volatile static APIHelper _Instance;
- public static APIHelper GetInstance => _Instance ?? (_Instance = new APIHelper());
- private APIHelper() { }
-
- public string PostData(string url, string data, string head)
- {
- byte[] b = Encoding.UTF8.GetBytes(data);//把字符串转换为二进制
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- request.Proxy = null;
- request.ContentType = "application/json";
- request.Method = "POST"; //设置请求方法
- request.ContentLength = b.Length; //设置长度
- request.Headers["Authorize"] = head;
- Stream postStream = request.GetRequestStream(); //requst流
- postStream.Write(b, 0, b.Length); //写入POST数据,二进制类型的
- postStream.Close(); //关闭
- HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //获取response
- Stream stream = response.GetResponseStream(); // 得到response响应流
- StreamReader sr = new StreamReader(stream);
- string str = sr.ReadToEnd(); //读取流
-
- sr.Close();
- stream.Close();
- return str;
- }
-
- public string GetData(string url, string head)
- {
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- request.Method = "GET";
- request.Accept = "text/html, application/xhtml+xml, */*";
- request.ContentType = "application/json";
- request.Headers["Authorize"] = head;
- byte[] buffer = Encoding.UTF8.GetBytes(head);
- request.ContentLength = buffer.Length;
- request.GetRequestStream().Write(buffer, 0, buffer.Length);
- HttpWebResponse response = (HttpWebResponse)request.GetResponse();
- using (StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
- {
- return myStreamReader.ReadToEnd();
- }
- }
-
- public string HttpRequest(string url, string head, object data, RequestType requestType)
- {
- if (requestType == RequestType.POST)
- {
- return PostData(url, JsonConvert.SerializeObject(data), head);
- }
- else
- {
- StringBuilder sb = new StringBuilder();
- sb.Append("?");
- foreach (System.Reflection.PropertyInfo p in data.GetType().GetProperties())
- {
- if (sb.ToString().Last() != '?')
- {
- sb.Append("&");
- }
- sb.Append(p.Name);
- sb.Append("=");
- sb.Append(p.GetValue(data));
- }
- return GetData(url + sb.ToString(), head);
- }
- }
-
- }
-
- public enum RequestType
- {
- POST,
- PUT,
- DELETE,
- GET
- }
- }
|