| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Configuration;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading.Tasks;
- using System.Timers;
- using WebScanner.Tools;
- namespace WebScanner
- {
- public class ScannerService
- {
- private ScannerService()
- {
- //int msInterval = Convert.ToInt16(ConfigurationManager.AppSettings["TimeSpan"]);
- int msInterval = AppSetting.GetInt("TimeInterval");
- Timer timer = new Timer();
- timer.Elapsed += Timer_Elapsed;
- timer.Enabled = true;
- timer.Interval = msInterval * 1000;
- }
- private void Timer_Elapsed(object sender, ElapsedEventArgs e)
- {
- //var ms = ConfigurationManager.AppSettings["HostApi"].ToString();
- var ms = AppSetting.GetValue("HostApi");
- var webs = ms.Split(';');
- foreach (var web in webs)
- {
- Action ac = () => HttpRequest(web, contenttype: "text/html; charset=utf-8");
- ac.Invoke();
- }
- }
- /// <summary>
- /// 不做catch处理,需要在外部做
- /// </summary>
- /// <param name="url"></param>
- /// <param name="method">默认GET,空则补充为GET</param>
- /// <param name="contenttype">默认json,空则补充为json</param>
- /// <param name="header">请求头部</param>
- /// <param name="data">请求body内容</param>
- /// <returns></returns>
- public static string HttpRequest(string url, string method = "GET", string contenttype = "application/json;charset=utf-8", Hashtable header = null, string data = null)
- {
- typeof(ScannerService).LogInfo($"request start:{url}");
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- request.Method = string.IsNullOrEmpty(method) ? "GET" : method;
- request.ContentType = string.IsNullOrEmpty(contenttype) ? "application/json;charset=utf-8" : contenttype;
- request.Timeout = 30000;
- if (header != null)
- {
- foreach (var i in header.Keys)
- {
- request.Headers.Add(i.ToString(), header[i].ToString());
- }
- }
- if (!string.IsNullOrEmpty(data))
- {
- Stream requestStream = request.GetRequestStream();
- byte[] bytes = Encoding.UTF8.GetBytes(data);
- requestStream.Write(bytes, 0, bytes.Length);
- requestStream.Close();
- }
- HttpWebResponse response = (HttpWebResponse)request.GetResponse();
- Stream responseStream = response.GetResponseStream();
- StreamReader streamReader = new StreamReader(responseStream ?? throw new InvalidOperationException(), Encoding.GetEncoding("utf-8"));
- string re = streamReader.ReadToEnd();
- streamReader.Close();
- responseStream.Close();
- typeof(ScannerService).LogInfo($"request end:{re.Substring(0,100)}");
- return re;
- }
- private static volatile ScannerService _scannerService = null;
- public static ScannerService GetSingleObj()
- {
- return _scannerService ?? (_scannerService = new ScannerService());
- }
- }
- }
|