Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom header in HttpWebRequest

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

like image 483
Nelson T Joseph Avatar asked Dec 15 '11 12:12

Nelson T Joseph


People also ask

Can I add custom header to HTTP request?

In the Home pane, double-click HTTP Response Headers. In the HTTP Response Headers pane, click Add... in the Actions pane. In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.

What are WebRequest headers?

The Headers property contains a WebHeaderCollection instance containing the header information to send to the Internet resource. The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by the descendant class returned by the WebRequest.

What is HttpWebRequest C#?

The HttpWebRequest class provides support for the properties and methods defined in WebRequest and for additional properties and methods that enable the user to interact directly with servers using HTTP.


2 Answers

You use the Headers property with a string index:

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

According to MSDN, this has been available since:

  • Universal Windows Platform 4.5
  • .NET Framework 1.1
  • Portable Class Library
  • 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

like image 96
Anders Marzi Tornblad Avatar answered Sep 17 '22 17:09

Anders Marzi Tornblad


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 = 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());         }     } 
like image 20
SharK Avatar answered Sep 19 '22 17:09

SharK