Add Custom Headers using HttpWebRequest

前端 未结 3 1023
深忆病人
深忆病人 2020-12-15 20:49

I am not really sure what type of headers these highlighted values are, but how should I add them using HttpWebRequest?

相关标签:
3条回答
  • 2020-12-15 20:56

    IMHO it is considered as malformed header data.

    You actually want to send those name value pairs as the request content (this is the way POST works) and not as headers.

    The second way is true.

    0 讨论(0)
  • 2020-12-15 21:02

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

    private static void WebRequest()
    {
        const string WEBSERVICE_URL = "<<Web Service URL>>";
        try
        {
            var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
            if (webRequest != null)
            {
                webRequest.Method = "GET";
                webRequest.Timeout = 20000;
                webRequest.ContentType = "application/json";
                webRequest.Headers.Add("Authorization", "Basic dcmGV25hZFzc3VudDM6cGzdCdvQ=");
                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());
        }
    }
    
    0 讨论(0)
  • 2020-12-15 21:10

    You should do ex.StackTrace instead of ex.ToString()

    0 讨论(0)
提交回复
热议问题