接口Get方法请求数据
/// 接口请求Get /// </summary> /// <param name="urlStr">接口地址</param> /// <param name="value">页眉参数</param> /// <param name="requestData">请求参数</param> /// <returns></returns> public static string HttpGetRequest(string urlStr, string Value, List<ApiValue.valueObj> requestData) { try { ///获取config中的apiUrl string apiUrl = ConfigurationManager.AppSettings["api-url"]; //构造查询参数 var query = HttpUtility.ParseQueryString(string.Empty); if (requestData != null && requestData.Count > 0) { foreach (ApiValue.valueObj valueObj in requestData) { query[valueObj.name] = valueObj.value; } } string url = apiUrl + urlStr + query.ToString(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "Get"; //页眉设置Header request.Headers.Add("Authorization", Value); request.Headers.Add("x-nexus-api-key", apiKey); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //获取到读取的数据 using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) { return streamReader.ReadToEnd(); } } catch (Exception ex) { throw new Exception(ex.Message); } }
接口Post方法请求
/// <summary> /// 接口请求Post /// </summary> /// <param name="urlStr">接口地址</param> /// <param name="requestData">请求参数</param> public static void HttpPostRequest(string urlStr, string requestData) { ///获取config中的apiUrl string apiUrl = ConfigurationManager.AppSettings["api-url"]; string url = apiUrl + urlStr; byte[] byteData = Encoding.UTF8.GetBytes(requestData); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteData.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(byteData, 0, byteData.Length); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) { string responseData = streamReader.ReadToEnd(); Console.WriteLine(responseData); } }
标签:string,Get,url,request,接口,requestData,Post,apiUrl From: https://www.cnblogs.com/MaoZhuaShi/p/18636335