远程获取http数据和提交数据

 

/// <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;
        }

 

posted @ 2021-07-01 09:39  lunawzh  阅读(115)  评论(0编辑  收藏  举报