123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Text;
- using Newtonsoft.Json;
- namespace WebAPIBase.Utils
- {
- /// <summary>
- /// 使用HttpWebRequest远程访问
- /// </summary>
- public class HttpWebRequestHelper
- {
- public static string RequestPost(string url, List<Dictionary<string, string>> 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<Dictionary<string, string>> 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;
- }
- }
- }
- }
|