在调用[按顺序请求] C#之前授权HTTP请求

时间:2019-03-13 11:59:22

标签: c# http oauth httpwebrequest access-token

除非访问令牌尚未过期,否则我需要在调用每个HTTP请求之前对其进行授权。

我想:  1.第一次获取访问令牌  2.检查令牌是否未过期  3.在下一个HTTP请求上包装返回的密钥

代码: 首先,我将System.Net.WebRequest用于HTTP请求, 然后请求返回一个令牌,然后将其包装在请求中。

HTTP请求:

        /// <summary>
    /// HTTP request without authintcation
    /// </summary>
    /// <param name="response">Returned HTTP Response from the request</param>
    /// <param name="req_url">Request URL to call</param>
    /// <param name="req_method">Request Method [GET, POST, PUT, DELETE, etc ...]</param>
    /// <param name="req_body">Request Body [JSON]</param>
    /// <returns>True if the request was successful; false otherwise.</returns>


    private static bool HTTP_Request_Web(out HttpWebResponse response, string req_url,
                                      string req_method, string req_body)
    {
        response = null;

        try
        {
            //Create request to URL.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(req_url);

            //Set request headers.
            request.KeepAlive = true;
            //request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36";
            request.Headers.Set(HttpRequestHeader.CacheControl, "no-cache");
            request.ContentType = "application/json";
            request.Accept = "*/*";
            request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            request.Headers.Set(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.9,ar;q=0.8");

            //Set request method
            request.Method = req_method;

            // Disable 'Expect: 100-continue' behavior. 
            request.ServicePoint.Expect100Continue = false;

            //Set request body.
            //string body = @"{
            //                 ""username"":""XXXX"",
            //                 ""password"":""XXXXXXX""
            //                }";
            byte[] postBytes = Encoding.UTF8.GetBytes(req_body);
            request.ContentLength = postBytes.Length;
            Stream stream = request.GetRequestStream();
            stream.Write(postBytes, 0, postBytes.Length);
            stream.Close();

            //Get response to request.
            response = (HttpWebResponse)request.GetResponse();
        }
        catch (WebException e)
        {
            //ProtocolError indicates a valid HTTP response, but with a non-200 status code (e.g. 304 Not Modified, 404 Not Found)
            if (e.Status == WebExceptionStatus.ProtocolError) response = (HttpWebResponse)e.Response;
            else return false;
        }
        catch (Exception)
        {
            if (response != null) response.Close();
            return false;
        }

        return true;
    }

之后,在下一个请求中使用令牌,如下图所示: Access Token

1 个答案:

答案 0 :(得分:0)

我使用了来自Magento的固定集成令牌。