Aggiungi un'intestazione personalizzata in HttpWebRequest


Risposte:


175

Utilizzi la Headersproprietà con un indice di stringa:

request.Headers["X-My-Custom-Header"] = "the-value";

Secondo MSDN, questo è disponibile da:

  • Piattaforma Windows universale 4.5
  • .NET Framework 1.1
  • Libreria di classi portabile
  • Silverlight 2.0
  • Windows Phone Silverlight 7.0
  • Windows Phone 8.1

https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers(v=vs.110).aspx


inoltre la stringa può essere sostituita con enum HttpRequestHeader come questo httpWebRequest.Headers [HttpRequestHeader.Authorization] = "value";
— OXXY

1
Questo non risponderebbe alla domanda originale, @OXXY. L' HttpRequestHeaderenumerazione è per le intestazioni standard, non per quelle personalizzate.
— Anders Tornblad

c'è una proprietà chiamata nome in google drive file upload api, che dovrebbe essere inviata tramite il metodo post. Quindi, request.Headers ["name"] = "hello.txt"; Quindi, non riflette. Qualche aiuto Cosa dovremmo usare per quelli personalizzati?
— Susarla Nikhilesh

I dati POST non vengono inviati tramite le intestazioni, quindi questo non è il posto giusto per la tua domanda. Pubblica una nuova domanda.
— Anders Tornblad

18

Un metodo semplice per creare il servizio, aggiungere intestazioni e leggere la risposta JSON,

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 = 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());
        }
    }

3
Authorizationnon è un'intestazione personalizzata e dovrebbe essere gestita in modo più controllato.
— Anders Tornblad

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.