Http上傳資料到介面get/post
阿新 • • 發佈:2021-11-03
/// <summary> /// 獲取介面json內容轉string /// </summary> /// <param name="url">請求介面地址</param> /// <returns></returns> public static string Get(string url) { string result = ""; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "Get"; //req.Headers.Add() try { HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Stream stream = resp.GetResponseStream(); //獲取內容 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { //獲取的資料返回值 result = reader.ReadToEnd(); } } catch (Exception ex) { result = ex.Message; } return result; }
public static string Post(string serviceAddress, string strContent) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress); request.Method = "POST"; request.ContentType = "application/json"; using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream())) { dataStream.Write(strContent); dataStream.Close(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string encoding = response.ContentEncoding; if (encoding == null || encoding.Length < 1) { encoding = "UTF-8"; //預設編碼 } StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); return reader.ReadToEnd(); }