Setting Authorization Header of HttpClient

前端 未结 21 2176
粉色の甜心
粉色の甜心 2020-11-22 14:53

I have an HttpClient that I am using for a REST API. However I am having trouble setting up the Authorization header. I need to set the header to the token I received from d

21条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 15:11

    this could works, if you are receiving a json or an xml from the service and i think this can give you an idea about how the headers and the T type works too, if you use the function MakeXmlRequest(put results in xmldocumnet) and MakeJsonRequest(put the json in the class you wish that have the same structure that the json response) in the next way

    /*-------------------------example of use-------------*/
    MakeXmlRequest("your_uri",result=>your_xmlDocument_variable =     result,error=>your_exception_Var = error);
    
    MakeJsonRequest("your_uri",result=>your_classwhateveryouwant_variable=result,error=>your_exception_Var=error)
    /*-------------------------------------------------------------------------------*/
    
    
    public class RestService
    {
        public void MakeXmlRequest(string uri, Action successAction, Action errorAction)
        {
            XmlDocument XMLResponse = new XmlDocument();
            string wufooAPIKey = ""; /*or username as well*/
            string password = "";
            StringBuilder url = new StringBuilder();
            url.Append(uri);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url.ToString());
            string authInfo = wufooAPIKey + ":" + password;
            authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
            request.Timeout = 30000;
            request.KeepAlive = false;
            request.Headers["Authorization"] = "Basic " + authInfo;
            string documento = "";
            MakeRequest(request,response=> documento = response,
                                (error) =>
                                {
                                 if (errorAction != null)
                                 {
                                    errorAction(error);
                                 }
                                }
                       );
            XMLResponse.LoadXml(documento);
            successAction(XMLResponse);
        }
    
    
    
        public void MakeJsonRequest(string uri, Action successAction, Action errorAction)
        {
            string wufooAPIKey = "";
            string password = "";
            StringBuilder url = new StringBuilder();
            url.Append(uri);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url.ToString());
            string authInfo = wufooAPIKey + ":" + password;
            authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
            request.Timeout = 30000;
            request.KeepAlive = false;
            request.Headers["Authorization"] = "Basic " + authInfo;
           // request.Accept = "application/json";
          //  request.Method = "GET";
            MakeRequest(
               request,
               (response) =>
               {
                   if (successAction != null)
                   {
                       T toReturn;
                       try
                       {
                           toReturn = Deserialize(response);
                       }
                       catch (Exception ex)
                       {
                           errorAction(ex);
                           return;
                       }
                       successAction(toReturn);
                   }
               },
               (error) =>
               {
                   if (errorAction != null)
                   {
                       errorAction(error);
                   }
               }
            );
        }
        private void MakeRequest(HttpWebRequest request, Action successAction, Action errorAction)
        {
            try{
                using (var webResponse = (HttpWebResponse)request.GetResponse())
                {
                    using (var reader = new StreamReader(webResponse.GetResponseStream()))
                    {
                        var objText = reader.ReadToEnd();
                        successAction(objText);
                    }
                }
            }catch(HttpException ex){
                errorAction(ex);
            }
        }
        private T Deserialize(string responseBody)
        {
            try
            {
                var toReturns = JsonConvert.DeserializeObject(responseBody);
                 return toReturns;
            }
            catch (Exception ex)
            {
                string errores;
                errores = ex.Message;
            }
            var toReturn = JsonConvert.DeserializeObject(responseBody);
            return toReturn;
        }
    }
    }
    

提交回复
热议问题