当先锋百科网

首页 1 2 3 4 5 6 7

最近公司项目需要对接Https接口,将对接的代码整理如下:

 1 public void Get()
 2 {
 3     HttpWebRequest request = null;
 4 request = WebRequest.Create("https://10.15.67.27:8073/api/tvwall") as HttpWebRequest;
 5 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
 6 request.ProtocolVersion = HttpVersion.Version11;
 7 // 这里设置了协议类型。
 8 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; ;// SecurityProtocolType.Tls1.2;
 9 request.KeepAlive = false;
10 ServicePointManager.CheckCertificateRevocationList = true;
11 ServicePointManager.DefaultConnectionLimit = 100;
12 ServicePointManager.Expect100Continue = false;
13 
14 request.Method = "GET"; //使用get方式发送数据
15 request.ContentType = "application/json";
16 request.Accept = "application/json";
17 request.Referer = null;
18 request.AllowAutoRedirect = true;
19 
20 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
21 Stream stream = response.GetResponseStream();
22 string result = string.Empty;
23 using (StreamReader sr = new StreamReader(stream))
24 {
25 result = sr.ReadToEnd();
26 }
27 Console.Write(result);
28 }

 

 1 public void Post()
 2 { 4 HttpWebRequest request = null;
 5 string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
 6 request = WebRequest.Create("https://10.15.67.27:8073/api/tvwall/25/scene/new") as HttpWebRequest;
 7 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
 8 request.ProtocolVersion = HttpVersion.Version11;
 9 // 这里设置了协议类型。
10 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // SecurityProtocolType.Tls1.2;
11 request.KeepAlive = false;
12 ServicePointManager.CheckCertificateRevocationList = true;
13 ServicePointManager.DefaultConnectionLimit = 100;
14 ServicePointManager.Expect100Continue = false;
15 
16 request.Method = "POST";
17 request.ContentType = "multipart/form-data; boundary=" + formDataBoundary;
18 request.Accept = "application/json";
19 request.Referer = null;
20 request.AllowAutoRedirect = true;
21 StringBuilder builder = new StringBuilder();
22 
23 foreach(var dic in parameters)
24 {
25 builder.AppendLine(string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
26 formDataBoundary,
27 dic.Key,
28 dic.Value));
29 }
30 builder.AppendLine(string.Format("--{0}--", formDataBoundary));
31 
32 byte[] formData = encoding.GetBytes(builder.ToString());37 
38 Stream newStream = request.GetRequestStream();
39 newStream.Write(formData, 0, formData.Length);
40 newStream.Close();
41 
42 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
43 Stream stream = response.GetResponseStream();
44 string result = string.Empty;
45 using (StreamReader sr = new StreamReader(stream))
46 {
47 result = sr.ReadToEnd();
48 }
49 Console.Write(result);
50 }

 

转载于:https://www.cnblogs.com/Johar/p/9089178.html