Camilson
Camilson

Reputation: 37

HttpClient add Host and UserAgent into request in c#

I have to add Host and User Agent to my request but there is no a function like "Host" or "User Agent"

without host I have unauthorized.. "WebException: The remote server returned an error: (401) Unauthorized." my code:

var webRequest = WebRequest.Create(url) as HttpWebRequest;
            if (webRequest != null)
            {
                webRequest.Accept = "*/*";
                webRequest.UserAgent = ".NET";
                webRequest.Method = WebRequestMethods.Http.Post;
                webRequest.ContentType = "application/json";
                webRequest.Host = "coinbase.com";

                var whc = new WebHeaderCollection
                {
                    "ACCESS_KEY: " + API_KEY,
                    "ACCESS_SIGNATURE: " + signature,
                    "ACCESS_NONCE: " + nonce
                };
                webRequest.Headers = whc;

                using (WebResponse response = webRequest.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(stream);
                        returnData = reader.ReadToEnd();
                    }
                }
            }

Screen of my code: screen

Upvotes: 3

Views: 3874

Answers (1)

Dávid Molnár
Dávid Molnár

Reputation: 11573

With the lines "webRequest.Accept = "/";" etc. you actually set up values in the webRequest.Headers collection. Then with the line "webRequest.Headers = whc;" you basically overwrite the whole collection. You should add the custom headers like this:

var webRequest = WebRequest.Create("http://google.com") as HttpWebRequest;
if (webRequest != null)
{
    webRequest.Accept = "*/*";
    webRequest.UserAgent = ".NET";
    webRequest.Method = WebRequestMethods.Http.Post;
    webRequest.ContentType = "application/json";
    webRequest.Host = "coinbase.com";

    webRequest.Headers.Add("ACCESS_KEY", API_KEY);
    webRequest.Headers.Add("ACCESS_SIGNATURE", signature);
    webRequest.Headers.Add("ACCESS_NONCE", nonce);

    //...
}

When I debuged this, I saw all the necessary headers in the webRequest.Headers collection, but the host was missing. If I added it then got error stating I should set the header with "webRequest.Host" and not directly in the headers collection. I don't know if this is an error or it should work like this... Maybe this won't bother you at all.

Upvotes: 1

Related Questions