通过Get/Post发起http请求
Get请求
public static string HttpGet(string url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; }
调用方法
string url = "https://openapi.mafengwo.cn/oauth2/token?client_id=1234&client_secret=5678"; var resStr = HttpGet(url);
Post请求
public static string Post(string url, string postData) { //请求 WebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; request.ContentLength = Encoding.UTF8.GetByteCount(postData); byte[] postByte = Encoding.UTF8.GetBytes(postData); Stream reqStream = request.GetRequestStream(); reqStream.Write(postByte, 0, postByte.Length); reqStream.Close(); //响应 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; }
调用方法
var str = string.Format("partnerId={0}&action={1}×tamp={2}&nonce={3}&data={4}&sign={5}&access_token={6}", partnerId, action, timestamp, nonce, data, sign, access_token); var responseData = Post("https://openapi.mafengwo.cn/deals/rest", str);