Http.cs
3.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using RestSharp;
using System;
using System.Collections.Generic;
namespace Model
{
public static class Http
{
public static bool Ping(string ip)
{
try
{
using System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingReply result = ping.Send(ip, 2000);
bool rtn = result.Status == System.Net.NetworkInformation.IPStatus.Success;
if (rtn)
LogNet.log.Info(string.Format("Ping {0} OK", ip));
else
LogNet.log.Info(string.Format("Ping {0} timeout", ip));
return rtn;
}
catch (Exception ex)
{
LogNet.log.Error("Ping", ex);
return false;
}
}
public static string Get(string url)
{
LogNet.log.Info("[GET]URL:" + url);
RestClient client = new(url) { Timeout = 10000 };
RestRequest request = new(Method.GET);
IRestResponse response = client.Execute(request);
string s = response.Content;
LogNet.log.Info("Return:" + s);
return FormatContent(s);
}
public static string Post(string url, Dictionary<string, string> param)
{
List<string> body = new();
foreach (string key in param.Keys)
body.Add(string.Format("{0}={1}", key, param[key]));
LogNet.log.Info("[Post]URL:" + url + " Body:" + string.Join(",", body));
RestClient client = new(url) { Timeout = 10000 };
RestRequest request = new(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
foreach(string key in param.Keys)
request.AddParameter(key, param[key]);
IRestResponse response = client.Execute(request);
string s = response.Content;
LogNet.log.Info("Return:" + s);
return FormatContent(s);
}
public static string PostJson<T>(string url,Dictionary<string,string> headers, T jsonobject)
{
RestClient client = new(url) { Timeout = 10000 };
RestRequest request = new(Method.POST);
request.AddHeader("Content-Type", "application/json");
if (headers != null)
{
foreach (var head in headers)
{
request.AddHeader(head.Key, head.Value);
}
}
request.AddJsonBody(jsonobject);
IRestResponse response = client.Execute(request);
string s = response.Content;
LogNet.log.Info("Return:" + s);
return s;
}
private static string FormatContent(string s)
{
if (string.IsNullOrWhiteSpace(s))
{
return "";
}
else
{
s = s.Replace("\n", "");
s = s.Replace("\r", "");
while (s.IndexOf(" ") >= 0)
s = s.Replace(" ", " ");
return s;
}
}
}
}