Add custom header in HttpWebRequest

后端 未结 3 1484
半阙折子戏
半阙折子戏 2020-11-30 02:38

I need to add some custom headers to the HttpWebRequest object. How can I add Custom Header to HttpWebRequest object in Windows Phone 7.

3条回答
  •  有刺的猬
    2020-11-30 03:17

    A simple method of creating the service, adding headers and reading the JSON response,

    private static void WebRequest()
        {
            const string WEBSERVICE_URL = "<>";
            try
            {
                var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
                if (webRequest != null)
                {
                    webRequest.Method = "GET";
                    webRequest.Timeout = 12000;
                    webRequest.ContentType = "application/json";
                    webRequest.Headers.Add("Authorization", "Basic dchZ2VudDM6cGFdGVzC5zc3dvmQ=");
    
                    using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
                    {
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                        {
                            var jsonResponse = sr.ReadToEnd();
                            Console.WriteLine(String.Format("Response: {0}", jsonResponse));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    

提交回复
热议问题