Skip to content

Instantly share code, notes, and snippets.

@dfch
Last active Sep 20, 2021
Embed
What would you like to do?
HttpClient and how to use Headers, Content-Type and PostAsync
// HttpClient and how to use Headers, Content-Type and PostAsync
// http://d-fens.ch/2014/04/12/httpclient-and-how-to-use-headers-content-type-and-postasync/
// Copyright 2014-2015 Ronald Rink, d-fens GmbH
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// NOTICE
// d-fens HttpClient
// this software contains work developed at
// d-fens GmbH, General-Guisan-Strasse 6, CH-6300 Zug, Switzerland
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
//using System.Json;
string Invoke(
string Method
,
string Uri
,
string Body
)
{
var cl = new HttpClient();
cl.BaseAddress = new Uri(Uri);
int _TimeoutSec = 90;
cl.Timeout = new TimeSpan(0, 0, _TimeoutSec);
string _ContentType = "application/json";
cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType));
var _CredentialBase64 = "RWRnYXJTY2huaXR0ZW5maXR0aWNoOlJvY2taeno=";
cl.DefaultRequestHeaders.Add("Authorization", String.Format("Basic {0}", _CredentialBase64));
var _UserAgent = "d-fens HttpClient";
// You can actually also set the User-Agent via a built-in property
cl.DefaultRequestHeaders.Add("User-Agent", _UserAgent);
// You get the following exception when trying to set the "Content-Type" header like this:
// cl.DefaultRequestHeaders.Add("Content-Type", _ContentType);
// "Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."
HttpResponseMessage response;
var _Method = new HttpMethod(Method);
switch (_Method.ToString().ToUpper())
{
case "GET":
case "HEAD":
// synchronous request without the need for .ContinueWith() or await
response = cl.GetAsync(Uri).Result;
break;
case "POST":
{
// Construct an HttpContent from a StringContent
HttpContent _Body = new StringContent(Body);
// and add the header to this object instance
// optional: add a formatter option to it as well
_Body.Headers.ContentType = new MediaTypeHeaderValue(_ContentType);
// synchronous request without the need for .ContinueWith() or await
response = cl.PostAsync(Uri, _Body).Result;
}
break;
case "PUT":
{
// Construct an HttpContent from a StringContent
HttpContent _Body = new StringContent(Body);
// and add the header to this object instance
// optional: add a formatter option to it as well
_Body.Headers.ContentType = new MediaTypeHeaderValue(_ContentType);
// synchronous request without the need for .ContinueWith() or await
response = cl.PutAsync(Uri, _Body).Result;
}
break;
case "DELETE":
response = cl.DeleteAsync(Uri).Result;
break;
default:
throw new NotImplementedException();
break;
}
// either this - or check the status to retrieve more information
response.EnsureSuccessStatusCode();
// get the rest/content of the response in a synchronous way
var content = response.Content.ReadAsStringAsync().Result;
return content;
}
// d-fens HttpClient
// this software contains work developed at
// d-fens GmbH, General-Guisan-Strasse 6, CH-6300 Zug, Switzerland
@Jtuffuor

This comment has been minimized.

Copy link

@Jtuffuor Jtuffuor commented Feb 9, 2017

hi, im try to integrate the beyonic api but i keep getting the statu code 401(UNAUTHORIZED). Any help please.
This is the code ;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net;

namespace NancyBeyonic.Modules
{
public class IndexModule : NancyModule
{
public IndexModule()
{
Get["/beyonic"] = parameters =>
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.BaseAddress = new Uri("https://app.beyonic.com");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/webhooks?Token=ab594c14986612f6167a975e1c369e71edab6900").Result;
return response;
};
}
}
}

@haneeshkb

This comment has been minimized.

Copy link

@haneeshkb haneeshkb commented Sep 8, 2019

Is there any way to add an integer value to the httpClient header request in c# ?
httpClient .DefaultRequestHeaders.Add(,) method only available ?

anyone please help on this?

@dfch

This comment has been minimized.

Copy link
Owner Author

@dfch dfch commented Sep 9, 2019

@haneeshkb

Is there any way to add an integer value to the httpClient header request in c# ?
httpClient .DefaultRequestHeaders.Add(,) method only available ?

As everything will be transmitted as text over http I see no issue transmitting integers. I would probably just convert them to strings and then send them. Maybe I do not fully understand your question or problem you encountered, but this is what I would do from my current point of view.

@haneeshkb

This comment has been minimized.

Copy link

@haneeshkb haneeshkb commented Sep 9, 2019

Hi dfch ,
Thanks for the response.
Actually I want to pass an integer value like this
{
int iVal =11
HttpClient tokenClient = new HttpClient();
tokenClient .DefaultRequestHeaders.Add("CUSTOM_FIELD", iVal); // this wont work anyway
}

'Add' method of DefaultRequestHeaders will only accept strings .
So I am looking for any other way to pass integer value for a custom header value .

@dfch

This comment has been minimized.

Copy link
Owner Author

@dfch dfch commented Sep 10, 2019

try iVal.ToString()

@MrArif-5

This comment has been minimized.

Copy link

@MrArif-5 MrArif-5 commented Nov 17, 2020

Kindly help me to foodics POS Integration

following are my code it (Asp.net web api C#)

using (var client = new HttpClient())
{
var url = "https://dev-dash.foodics.com/api/v2/orders";
var cl = new HttpClient();
cl.BaseAddress = new Uri(url);
int _TimeoutSec = 90;
cl.Timeout = new TimeSpan(0, 0, _TimeoutSec);
string _ContentType = "application/json";
cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + obj.Token);
var response = await client.GetStringAsync(url);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment