GET和POST传值失败,多半是传输的字符串和URL的事
1 public static string ExcuteGetToken(string serviceUrl, string ReqInfo, string token) 2 { 3 using (null) 4 { 5 ServicePointManager.ServerCertificateValidationCallback += ValidateServerCertificate; 6 ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; 7 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; 8 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceUrl); 9 request.CookieContainer = new CookieContainer(); 10 request.Headers.Add("userName", "abc"); //设置信息头用户名 11 request.Headers.Add("password", "123456"); //设置信息头密码 12 request.Headers.Add("Token", token); 13 request.KeepAlive = true; 14 request.Method = "GET"; 15 request.ContentType = "application/x-www-form-urlencoded"; 16 //添加发送数据 17 Encoding encoding = Encoding.GetEncoding("utf-8"); 18 if (!ReqInfo.Equals("")) 19 { 20 ReqInfo = "request=" + ReqInfo; 21 byte[] postData = encoding.GetBytes(ReqInfo); 22 request.ContentLength = postData.Length; 23 Stream requestStream = request.GetRequestStream(); 24 requestStream.Write(postData, 0, postData.Length); 25 } 26 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 27 //获取返回数据 28 Stream responseStream = response.GetResponseStream(); 29 if (responseStream == null) return ""; 30 StreamReader streamReader = new StreamReader(responseStream, encoding); 31 string retString = streamReader.ReadToEnd(); 32 streamReader.Close(); 33 responseStream.Close(); 34 return retString; 35 } 36 }
post方法
public static string ExcutePostToken(string serviceUrl, string ReqInfo,string token) { using (null) { ServicePointManager.ServerCertificateValidationCallback += ValidateServerCertificate; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceUrl); request.CookieContainer = new CookieContainer(); request.Headers.Add("userName", "abc"); //设置信息头用户名 request.Headers.Add("password", "123456"); //设置信息头密码 request.Headers.Add("token", token); request.KeepAlive = true; request.Method = "POST"; request.ContentType = "application/json"; //添加发送数据 if (!ReqInfo.Equals("")) { Encoding encoding = Encoding.GetEncoding("utf-8"); byte[] postData = encoding.GetBytes(ReqInfo); request.ContentLength = postData.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(postData, 0, postData.Length); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //获取返回数据 Stream responseStream = response.GetResponseStream(); if (responseStream == null) return ""; StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); string retString = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); return retString; } } private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }