include raw text in http get request in c# backend code - c#

I have this code:
client.BaseAddress = new Uri("https://sandbox-quickbooks.api.intuit.com/v3/company/1232/vendor/70?minorversion=8");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization
= new AuthenticationHeaderValue("Bearer", "bLpuw.vjbvIP_P7Vyj4ziSGa3Ohg");
using (HttpResponseMessage response = client.PostAsync("https://sandbox-quickbooks.api.intuit.com/v3/company/1232/query?minorversion=8").Result)
{
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().Result;
}
}
Per the quickbooks api Postman sample they include raw text query in the http post action.
Example:
How can I include the raw text in my c# post request?

You need to pass content to PostAsync method just like this
var myContent = "your string in here";
var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);
using (HttpResponseMessage response = client.PostAsync("https://sandbox-quickbooks.api.intuit.com/v3/company/1232/query?minorversion=8",bytecontent).Result)
{
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().Result;
}
}

Create a StringContent() with the text in it and pass it to the PostAsync().
You might need to check what Content-Type header is expected and pass that to the StringContent constructor as well.
E.g.
using (var requestContent = new StringContent(“any text”, Encoding.UTF8, “text/plain”))
{
... httpClient.PostAsync(url, requestContent)...
}

client.BaseAddress = new Uri("https://sandbox-quickbooks.api.intuit.com/v3/company/1232/vendor/70?minorversion=8");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization
= new AuthenticationHeaderValue("Bearer", "bLpuw.vjbvIP_P7Vyj4ziSGa3Ohg");
var postContent = new StringContent("myContent");
using (HttpResponseMessage response = client.PostAsync("https://sandbox-quickbooks.api.intuit.com/v3/company/1232/query?minorversion=8", postContent).Result)
{
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().Result;
}
}
Also, please be aware that you have some wrong use of the Async methods, you should always await instead of using the blocking Result property from the task.

Related

How to split an HTTP Request Body in two parts?

I'm fairly new to use HTTPClient and sending REST requests to APIs, I'm currently practicing multipart upload using this Google Drive API endpoint:
POST https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart
There's an instruction that states there to split the request body into two parts, I tried to recreate this but was unable to do so.
https://developers.google.com/drive/api/guides/manage-uploads#multipart
Here's my current code:
async void UploadFile(StorageFile fileName)
{
using (HttpClient client = new HttpClient())
{
// Opens files and convert it to stream
var resultStream = await fileName.OpenReadAsync();
var fileStreamContent = new StreamContent(resultStream.AsStream());
// Create file MetaData
var fileMetaData = JsonConvert.SerializeObject(
new { name = fileName.Name, mimetype = fileName.ContentType });
// Create POST request
var requestMessage = new HttpRequestMessage(HttpMethod.Post, uploadFileEndpoint);
requestMessage.Headers.Authorization = new AuthenticationHeaderValue(tokenType, accessToken);
// Add request body
requestMessage.Content = new StringContent(fileMetaData, Encoding.UTF8, "application/json");
requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/related");
var response = await client.SendAsync(requestMessage);
string responseString = await response.Content.ReadAsStringAsync();
output(responseString);
}
}
Any help would be greatly appreciated, thank you!
According to the documentation on Perform a multipart upload (HTTP tab), you need the MultipartFormDataContent as suggested by #Jeremy.
There are a few things needed to perform/migrate:
Add AuthenticationHeaderValue into client.DefaultRequestHeaders.Authorization.
Create a StreamContent instance, fileStreamContent (which you have done) and specify its Headers.ContentType.
Create a StringContent instance, stringContent (which you have done).
Append both StreamContent and StringContent into the MultipartFormDataContent instance, formData.
Specify the formData's Headers.ContentType as requested in API docs.
Post the formData with await client.PostAsync(/* API Url */, formData);
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, accessToken);
// Opens files and convert it to stream
var resultStream = await fileName.OpenReadAsync();
var fileStreamContent = new StreamContent(resultStream.AsStream());
fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue(fileName.ContentType);
// Create file MetaData
var fileMetaData = JsonConvert.SerializeObject(new { name = fileName.Name, mimetype = fileName.ContentType });
var stringContent = new StringContent(fileMetaData, Encoding.UTF8, "application/json");
// Create POST request
MultipartFormDataContent formData = new MultipartFormDataContent();
formData.Add(stringContent, "metadata");
formData.Add(fileStreamContent, "media");
formData.Headers.ContentType = new MediaTypeHeaderValue("multipart/related");
var response = await client.PostAsync(uploadFileEndpoint, formData);
string responseString = await response.Content.ReadAsStringAsync();
}

How to read header values with HttpClient in .net core

This is the code i'm using
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", HttpContext.Session.GetString("JwtToken"));
var url = $"...some url";
var requestUri = new Uri(url);
var responseTask = client.GetAsync(requestUri);
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var reportResults = Task.Run(async() => await result.Content.ReadAsAsync<JArray>()).Result;
return reportResults;
}
}
Here if i try to access header like this
string error = responseTask.Headers.TryGetValue("X-TotalResults").FirstOrDefault();
I'm getting error
Task<HttpResponseMessage> does not contain a
definition for Headers and no accessible extension method Headers
So How i can read the header .. thanks in advance
You have a Task<HttpResponseMessage> rather than a HttpResponseMessage.
Instead of using .Result, which is dangerous for many reasons, convert your code to use async properly.
static HttpClient client = new HttpClient();
private async JArray GetReportResults()
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", HttpContext.Session.GetString("JwtToken"));
var url = $"...some url";
using (var response = await client.GetAsync(url))
{
result.EnsureSuccessStatusCode()
var reportResults = await result.Content.ReadAsAsync<JArray>();
return reportResults;
}
}

How do I pass X-HTTP-METHOD-Override Header to C#s HttpClient

I try to update a field using REST in C#. Using PatchAsync did not work so far, so I'm trying to use PUT instead, but now I need to pass the X-HTTP-METHOD-Override Header and I have no idea how to do this.
I've looked at the available headers for the DefaultRequestHeaders, but I could not find anything.
This is what I have got so far:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BASEURL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = CreateAuthHeader();
var requestBody = new Dictionary<string, string>
{
{ "price", price.ToString() }
};
var jsonRequest = JsonConvert.SerializeObject(requestBody);
var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json-patch+json");
var response = new HttpResponseMessage();
response = await client.PutAsync($"{APIBASE}/data/ProductAttribute/{attributeId}", content).ConfigureAwait(false);
This should work like normal:
client.DefaultRequestHeaders.Add("X-HTTP-METHOD-Override", "PATCH");
I'm assuming you want PATCH as verb.

POST Request with json in c#

I am attempting to do a POST request which I have got working through Postman but I am getting a 400 error when done from code.
I am trying to reach the POST endpoint from here: http://developer.oanda.com/rest-live-v20/order-ep/
Here is my code, does anything look incorrect or have I missed anything?
public void MakeOrder(string UID)
{
string url = $"https://api-fxpractice.oanda.com/v3/accounts/{UID}/orders";
string body = "{'order': {'units': '10000', 'instrument': 'EUR_USD', 'timeInForce': 'FOK', 'type': 'MARKET', 'positionFill': 'DEFAULT'}}";
using (WebClient client = new WebClient())
{
client.Headers.Add("Authorization", "Bearer 11699873cb44ea6260ca3aa42d2898ac-2896712134c5924a25af3525d3bea9b0");
client.Headers.Add("Content-Type", "application/json");
client.UploadString(url, body);
}
}
I'm very new to coding so apologies if it is something very simple.
use HttpClient from System.Net.Http:
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using (var httpClient = new HttpClient())
{
string url = $"https://api-fxpractice.oanda.com/v3/accounts/{UID}/orders";
string body = "{'order': {'units': '10000', 'instrument': 'EUR_USD', 'timeInForce': 'FOK', 'type': 'MARKET', 'positionFill': 'DEFAULT'}}";
var content = new StringContent(body , Encoding.UTF8, "application/json");
var result = httpClient.PostAsync(url, content).Result;
var contents = result.Content.ReadAsStringAsync();
}
I would suggest you to use HttpClient over WebClient. You can find here the difference.
using (var httpClient = new HttpClient())
{
string url = $"https://api-fxpractice.oanda.com/v3/accounts/{UID}/orders";
string body = "{'order': {'units': '10000', 'instrument': 'EUR_USD', 'timeInForce': 'FOK', 'type': 'MARKET', 'positionFill': 'DEFAULT'}}";
var content = new StringContent(body, Encoding.UTF8, "application/json");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTIzMDY0NTQsImlzcyI6IlRlc3QuY29tIiwiYXVkIjoiVGVzdC5jb20ifQ.c-3boD5NtOEhXNUnzPHGD4rY1lbEd-pjfn7C6kDPbxw");
var result = httpClient.PostAsync(url, content).Result;
var contents = result.Content.ReadAsStringAsync();
}

Set Authorization/Content-Type headers when call HTTPClient.PostAsync

Where can I set headers to REST service call when using simple HTTPClient?
I do :
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{"id", "111"},
{"amount", "22"}
};
var content = new FormUrlEncodedContent(values);
var uri = new Uri(#"https://some.ns.restlet.uri");
var response = await client.PostAsync(uri, content);
var responseString = await response.Content.ReadAsStringAsync();
UPD
Headers I want to add:
{
"Authorization": "NLAuth nlauth_account=5731597_SB1, nlauth_email=xxx#xx.com, nlauth_signature=Pswd1234567, nlauth_role=3",
"Content-Type": "application/json"
}
Should I do the following?
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "NLAuth nlauth_account=5731597_SB1, nlauth_email=xxx#xx.com, nlauth_signature=Pswd1234567, nlauth_role=3","Content-Type":"application/json");
The way to add headers is as follows:
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");
Or if you want some custom header:
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("HEADERNAME", "HEADERVALUE");
This answer has SO responses already, see below:
Adding headers when using httpClient.GetAsync
Setting Authorization Header of HttpClient
UPDATE
Seems you are adding two headerrs; authorization and content type.
string authValue = "NLAuth nlauth_account=5731597_SB1,nlauth_email=xxx#xx.com, nlauth_signature=Pswd1234567, nlauth_role=3";
string contentTypeValue = "application/json";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authValue);
client.DefaultRequestHeaders.Add("Content-Type", contentTypeValue);
I know this was asked a while ago, but Juan's solution didn't work for me.
(Also, pretty sure this question is duplicated here.)
The method that finally worked was to use HttpClient with HttpRequestMessage and HttpResponseMessage.
Also note that this is using Json.NET from Newtonsoft.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using Newtonsoft.Json;
namespace NetsuiteConnector
{
class Netsuite
{
public void RunHttpTest()
{
Task t = new Task(TryConnect);
t.Start();
Console.WriteLine("Connecting to NS...");
Console.ReadLine();
}
private static async void TryConnect()
{
// dummy payload
String jsonString = JsonConvert.SerializeObject(
new NewObj() {
Name = "aname",
Email = "someone#somewhere.com"
}
);
string auth = "NLAuth nlauth_account=123456,nlauth_email=youremail#somewhere.com,nlauth_signature=yourpassword,nlauth_role=3";
string url = "https://somerestleturl";
var uri = new Uri(#url);
HttpClient c = new HttpClient();
c.BaseAddress = uri;
c.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", auth);
c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, url);
req.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
HttpResponseMessage httpResponseMessage = await c.SendAsync(req);
httpResponseMessage.EnsureSuccessStatusCode();
HttpContent httpContent = httpResponseMessage.Content;
string responseString = await httpContent.ReadAsStringAsync();
Console.WriteLine(responseString);
}
}
class NewObj
{
public string Name { get; set; }
public string Email { get; set; }
}
}
The other answers do not work if you are using an HttpClientFactory, and here's some reasons why you should. With an HttpClientFactory the HttpMessages are reused from a pool, so setting default headers should be reserved for headers that will be used in every request.
If you just want to add a content-type header you can use the alternate PostAsJsonAsync or PostAsXmlAsync.
var response = await _httpClient.PostAsJsonAsync("account/update", model);
Unfortunately I don't have a better solution for adding authorization headers than this.
_httpClient.DefaultRequestHeaders.Add(HttpRequestHeader.Authorization.ToString(), $"Bearer {bearer}");
On dotnet core 3.1 trying to run the top answer:
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Content-Type", "application/x-msdownload");
threw an exception: System.InvalidOperationException: Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.
What worked for me was to instead set HttpContent.Headers -> HttpContentHeaders.ContentType property with a MediaTypeHeaderValue value:
HttpClient client = new HttpClient();
var content = new StreamContent(File.OpenRead(path));
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-msdownload");
var post = client.PostAsync(myUrl, content);
I prefer to cache the httpClient so I avoid setting headers which could affect other requests and use SendAsync
var postRequest = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
postRequest.Headers.Add("Content-Type", "application/x-msdownload");
var response = await httpClient.SendAsync(postRequest);
var content = await response.Content.ReadAsStringAsync();

Categories

Resources