using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using Newtonsoft.Json; namespace WebAPIBase.Utils { /// /// 使用HttpWebRequest远程访问 /// public class HttpWebRequestHelper { public static string RequestPost(string url, List> requestdata) { try { string requestBody = ""; byte[] postData = null; if (requestdata != null) { requestBody = JsonConvert.SerializeObject(requestdata); //using (Stream postStream = new MemoryStream()) //{ // byte[] postData = Encoding.ASCII.GetBytes(requestBody); // postStream.Write(postData, 0, postData.Length); //} postData = Encoding.UTF8.GetBytes(requestBody); } HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.ContentType = "application/json"; //req.MediaType = "application/json"; //req.Accept = "application/json"; req.Method = "POST"; req.ContentLength = postData == null ? 0 : postData.Length; //WebHeaderCollection headers = new WebHeaderCollection(); //headers.Add("Authorization: Token" + authtoken); //httpWebRequest.Headers = headers; if (!string.IsNullOrEmpty(requestBody)) { using (Stream postStream = req.GetRequestStream()) { postStream.Write(postData, 0, postData.Length); } } HttpWebResponse res = (HttpWebResponse)req.GetResponse(); // Fails on this line. using (StreamReader streamReader = new StreamReader(res.GetResponseStream())) { string json = streamReader.ReadToEnd(); //LogHelper.Info("request json:" + json); return json; } } catch (Exception ex) { throw; } } public static string RequestGet(string url, List> requestdata) { var loginName = ""; var pwd = ""; foreach(var item in requestdata) { if(item.ContainsKey("loginName")) { loginName = item["loginName"]; } if(item.ContainsKey("pwd")) { pwd = item["pwd"]; } } url = url + "?loginName=" + loginName + "&pwd=" + pwd; NLog.LogManager.GetCurrentClassLogger().Info("url:" + url); try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); //req.ContentType = "application/json"; //req.MediaType = "application/json"; //req.Accept = "application/json"; req.Method = "GET"; HttpWebResponse res = (HttpWebResponse)req.GetResponse(); // Fails on this line. using (StreamReader streamReader = new StreamReader(res.GetResponseStream())) { string json = streamReader.ReadToEnd(); //LogHelper.Info("request json:" + json); return json; } } catch (Exception ex) { throw; } } } }