0%

HttpWeb补充

前面啥也没有

HttpWeb说明

HttpWeb

补充

解决SSL/TLS证书验证报错

1
2
3
4
5
6
7
8
9
10
11
12
13
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;

//忽略SSL验证
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;

//添加SSL证书
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 |
SecurityProtocolType.Tls |
(SecurityProtocolType)0x300 |//Tls11
(SecurityProtocolType)0xC00;//Tls12

Client

1
2
3
4
5
6
7
8
9
10
11

WebClient web = new WebClient();
web.Headers.Add(HttpRequestHeader.ContentType, "application/json");
web.Encoding = Encoding.UTF8;
//post
recv = web.UploadString(mesGetVInfoUrl, jsonGetCurVehicle.ToString());
//request
recv = web.DownloadString(url);
var recvObject = JObject.Parse(recv)
JsonRecv jrecv = JsonConvert.DeserializeObject<JsonRecv>(recv);

Server

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
HttpListener httpListenner;
httpListenner = new HttpListener();
httpListenner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
httpListenner.Prefixes.Add(httpServerUrl);
httpListenner.Start();
new Thread(new ThreadStart(delegate
{
loop(httpListenner);
})).Start();

private void loop(HttpListener httpListenner)
{
while (true)
{
HttpListenerContext context = httpListenner.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
if (request.HttpMethod == "POST")
{
HandlePost(request, response);
}
else if (request.HttpMethod == "GET")
{
response.OutputStream.Write(Encoding.ASCII.GetBytes("NotSupport"), 0, Encoding.ASCII.GetBytes("NotSupport").Length);
}
response.Close();
}
}
public virtual void HandlePost(HttpListenerRequest request, HttpListenerResponse response)
{
var stream = response.OutputStream;
byte[] readBytes = new byte[1024];
request.InputStream.Read(readBytes, 0, 1024);
string recv = Encoding.ASCII.GetString(readBytes);

var jsonRecv = JObject.Parse(recv.Trim('\0'));
JObject jsonSend = new JObject();
if (jsonRecv["stationCode"].ToString() == "EV")
{
jsonSend["factoryCode"] = "Changzhou";
jsonSend["stationCode"] = "EV";
jsonSend["vin"] = "12345678901234567";
jsonSend["state"] = "Start";
jsonSend["result"] = "OK";
}
stream.Write(Encoding.ASCII.GetBytes(jsonSend.ToString()), 0, Encoding.ASCII.GetBytes(jsonSend.ToString()).Length);
}