你的位置:首页 > 操作系统

[操作系统]webservice 接口通过 HTTP 获取数据


 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Net; 6 using System.Text; 7 using System.IO; 8  9 namespace testRsa10 {11 public class GetDataByHttp12 {13 14 15 public static string DoPost(string url, string data)16 {17 HttpWebRequest req = GetWebRequest(url, "POST");18 byte[] postData = Encoding.UTF8.GetBytes(data);19 Stream reqStream = req.GetRequestStream();20 reqStream.Write(postData, 0, postData.Length);21 reqStream.Close();22 HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();23 Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);24 return GetResponseAsString(rsp, encoding);25 }26 27 public static HttpWebRequest GetWebRequest(string url, string method)28 {29 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);30 req.ServicePoint.Expect100Continue = false;31 req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";32 req.ContentType = "text/json";33 req.Method = method;34 req.KeepAlive = true;35 req.UserAgent = "guanyisoft";36 req.Timeout = 1000000;37 req.Proxy = null;38 return req;39 }40 41 public static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)42 {43 StringBuilder result = new StringBuilder();44 Stream stream = null;45 StreamReader reader = null;46 try47 {48 // 以字符流的方式读取HTTP响应49 stream = rsp.GetResponseStream();50 reader = new StreamReader(stream, encoding);51 // 每次读取不大于256个字符,并写入字符串52 char[] buffer = new char[256];53 int readBytes = 0;54 while ((readBytes = reader.Read(buffer, 0, buffer.Length)) > 0)55 {56 result.Append(buffer, 0, readBytes);57 }58 }59 finally60 {61 // 释放资源62 if (reader != null) reader.Close();63 if (stream != null) stream.Close();64 if (rsp != null) rsp.Close();65 }66 67 return result.ToString();68 }69 70 71 72 }73 }74   

View Code