You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks;
namespace ICSSoft.Common { public class HTTPHelper { private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static string HttpPost(string apiName, string url, string body) { try { //log.Debug(url + Environment.NewLine + body);
Encoding encoding = Encoding.UTF8; System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); request.Method = "POST"; request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
request.ContentType = "application/json; charset=utf-8"; // request.ContentType = "text/html, application/xhtml+xml";
byte[] buffer = encoding.GetBytes(body); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), encoding)) { return reader.ReadToEnd(); } } catch (System.Net.WebException ex) { log.Error(ex.ToString() + Environment.NewLine + url + Environment.NewLine + body); throw new Exception(apiName + "调用失败," + ex.Message); } }
public static string RestFulGet(string jsonParam, string url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); Encoding encoding = Encoding.UTF8; request.Method = "GET"; request.ContentType = "application/x-www-form-urlencoded"; request.Credentials = CredentialCache.DefaultCredentials;
request.Headers.Add("Content-Type", "application/json"); request.Headers.Add("Accept", "application/json"); request.Headers.Add("Authorization", "Basic TEST:12345678");
byte[] buffer = encoding.GetBytes(jsonParam); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length);
string str = string.Empty; WebResponse response = null; try { response = request.GetResponse(); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) response = (WebResponse)ex.Response; } if (response != null) { using (StreamReader st = new StreamReader(response.GetResponseStream(), encoding)) { str = System.Web.HttpUtility.UrlDecode(st.ReadToEnd()); } } return str; } } }
|