遠端獲取http資料和提交資料
阿新 • • 發佈:2021-07-01
/// <summary> /// /// 獲取遠端http Api資料 /// </summary> /// <param name="Url"></param> /// <returns></returns> public static string HttpData(string Url,string method="GET") { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method=method; request.ContentType = "application/json"; //request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr); //Stream myRequestStream = request.GetRequestStream(); //StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));//myStreamWriter.Write(postDataStr); //myStreamWriter.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; } /// <summary> /// post請求 /// 把引數以Post方式遠端提交併返回結果 /// </summary> /// <param name="Url"></param> /// <param name="message"></param> /// <returns></returns> public static async Task<T> DoPost<T>(string Url, object message) where T : new() { var res = new T(); string jsonContent = JsonConvert.SerializeObject(message); string responseBody = string.Empty; using (HttpClient httpClient = new HttpClient()) { var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); httpClient.DefaultRequestHeaders.Add("Method", "Post"); HttpResponseMessage response = await httpClient.PostAsync(Url, content); response.EnsureSuccessStatusCode(); responseBody = await response.Content.ReadAsStringAsync(); res = (T)JsonConvert.DeserializeObject<T>(responseBody); } return res; }