后端访问API接口

很简单,直接上代码

    /// 
    /// POST请求
    /// 
    /// 
    /// 
    /// 
    private static string HttpPost(string actionAndMethod, string body)
    {
        try
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(LoginHelper.ServerAddress + "/" + actionAndMethod);
            request.Method = "POST";
            request.Accept = "text/html,application/xhtml+xml,*/*";
            request.ContentType = "application/json";
            request.Headers.Add("authorization", “Token”);
            byte[] buffer = encoding.GetBytes(body);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
        catch (Exception)
        {
        }
    }

    /// 
    /// Get请求
    /// 
    /// server/action/method
    /// condition
    /// 
    private static string HttpGet(string actionAndMethod, Dictionary query = null)
    {
        try
        {
            var url = LoginHelper.ServerAddress + "/" + actionAndMethod;
            if (query != null)
            {
                var list = new List();
                foreach (var item in query)
                {
                    list.Add($"{item.Key}={item.Value}");
                }
                url += "?" + string.Join("&", list);
            }
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Accept = "text/html,application/xhtml+xml,*/*";
            request.ContentType = "application/json";
            request.Headers.Add("REMOTE_ADDR", IPHelper.GetLocalIP());
            request.Headers.Add("authorization", “Token”);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
        catch (Exception)
        {
        }
    }

你可能感兴趣的:(.NET项目实战,后端访问API接口)