C#通过请求url调用接口返回数据

 方法描述:通过请求url,调用对方系统的接口,拿到数据并返回;

方法参数:访问系统的url地址

url请求参数:searchDate(当前请求的年月:2023-7),需进行url编码

public string GetDataByRequestUrl(string url)
{

    requestUrl = url + "&searchDate:" +             System.Web.HttpUtility.UrlEncode( DateTime.Now.Year.ToString() + "-" +             DateTime.Now.Month.ToString());
    //请求url
    HttpWebRequest webRequest= (HttpWebRequest)WebRequest.Create(requestUrl);
    webRequest.Method="GET";
    webRequest.ContentType = "text/html;charset=UTF-8";

    //返回数据
    HttpWebResponse webResponse=(HttpWebResponse)webRequest.GetResponse();
    Stream myResponseStream = webResponse.GetResponseStream();
    StreamReader myStreamReader = new StreamReader(myResponseStream,     Encoding.GetEncoding("utf-8"));
    string retString = myStreamReader.ReadToEnd();
    myStreamReader.Close();
    myResponseStream.Close();
    return retString ;
}

你可能感兴趣的:(c#)