1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Net; 6 using System.Text; 7 using System.Threading.Tasks; 8 9 namespace TheDataTransfer.Dao 10 { 11 class Transfer 12 { 13 /* 14 * url:POST请求地址 15 * postData:json格式的请求报文,例如:{"key1":"value1","key2":"value2"} 16 */ 17 18 public static string PostJsonUrl(string url, string postData) 19 { 20 string result = ""; 21 22 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); 23 24 req.Method = "POST"; 25 26 req.Timeout = 800;//设置请求超时时间,单位为毫秒 27 28 req.ContentType = "application/json"; 29 30 byte[] data = Encoding.UTF8.GetBytes(postData); 31 32 req.ContentLength = data.Length; 33 34 using (Stream reqStream = req.GetRequestStream()) 35 { 36 reqStream.Write(data, 0, data.Length); 37 38 reqStream.Close(); 39 } 40 41 HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 42 43 Stream stream = resp.GetResponseStream(); 44 45 //获取响应内容 46 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) 47 { 48 result = reader.ReadToEnd(); 49 } 50 51 return result; 52 } 53 54 55 56 public static string PostXmlUrl(string url, string Data) 57 { 58 string result = ""; 59 60 StreamWriter myWriter = null; 61 62 HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url); 63 objRequest.Method = "POST"; 64 objRequest.ContentLength = Data.Length; 65 objRequest.ContentType = "text/xml";//提交xml 66 //objRequest.ContentType = "application/x-www-form-urlencoded";//提交表单 67 try 68 { 69 myWriter = new StreamWriter(objRequest.GetRequestStream()); 70 myWriter.Write(Data); 71 } 72 catch (Exception e) 73 { 74 return e.Message; 75 } 76 finally 77 { 78 myWriter.Close(); 79 } 80 81 HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse(); 82 using (StreamReader sr = new StreamReader(objResponse.GetResponseStream())) 83 { 84 result = sr.ReadToEnd(); 85 sr.Close(); 86 } 87 return result; 88 } 89 90 91 92 protected string GetWebContent(string url) 93 { 94 Stream outstream = null; 95 Stream instream = null; 96 StreamReader sr = null; 97 HttpWebResponse response = null; 98 HttpWebRequest request = null; 99 // 要注意的这是这个编码方式,还有内容的Xml内容的编码方式 100 Encoding encoding = Encoding.GetEncoding("GBK"); 101 byte[] data = encoding.GetBytes(url); 102 103 // 准备请求,设置参数 104 request = WebRequest.Create(url) as HttpWebRequest; 105 request.Method = "POST"; 106 //request.ContentType = "text/plain"; 107 request.ContentLength = data.Length; 108 109 outstream = request.GetRequestStream(); 110 outstream.Write(data, 0, data.Length); 111 outstream.Flush(); 112 outstream.Close(); 113 //发送请求并获取相应回应数据 114 115 response = request.GetResponse() as HttpWebResponse; 116 //直到request.GetResponse()程序才开始向目标网页发送Post请求 117 instream = response.GetResponseStream(); 118 sr = new StreamReader(instream, encoding); 119 //返回结果网页(html)代码 120 121 string content = sr.ReadToEnd(); 122 return content; 123 } 124 } 125 }