How do you add this big header in POST request in C#? - c#

I've found quite a lot of answers with regards to my question yet I am sure that I am doing something wrong because none really works and I just want to pass my own cookie session as well as the token and some other information from header when sending a POST request to server. This is being executed when button is pressed on the application:
private void button1_Click(object sender, EventArgs e)
{
PostRequest("https://www.example.com");
}
--
async static void PostRequest(string url)
{
//PASS HEADER HERE
//POST DATA
IEnumerable<KeyValuePair<string, string>> queries = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("data1": "name"),
new keyvaluepair<string, string>("data2": "555")
};
HttpContent q = new FormUrlEncodedContent(queries);
using (HttpClient client = new HttpClient()) //using for disposing if not in use
{
using (HttpResponseMessage response = await client.PostAsync(url, q)) //url, content in postAsync
{
using (HttpContent content = response.Content) //store content (data) into a 'content'
{
string mycontent = await content.ReadAsStringAsync();
//HttpContentHeaders headers = content.Headers;
Console.WriteLine(mycontent);
}
}
}
}
--
This is the cookie I want to pass and and the token along with other info in header:
POST /test/data HTTP/1.1
Host: host.datanet.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0
Accept: */*
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate, br
Content-Type: application/json
X-XSRF-TOKEN: eyJpdiI6ImxXMHNNQ01RT0RHTEMreU9lc0duZWc9PSIsInZhbHVlIjoiZ08zMFJDaTlZV1h5ZHlVRDBzUkFNNXBlY0ZuTFlCQ2V0SlVpRlpJRUUrRUl0NlwvUE1zN1Vza2F5blhDTStNM2NlM05VNXFZc1IxclNPSHhkNkU5Mmt3PT0iLCJtYWMiOiJmMGQxZTg5YmRlYjNmMzNjMWZlN2ZlM2E5YmE1NzRiMTgyMDQ5NDY1ZGZjNjliMDJlNDA2MGQzMjc3MjU2MzE2In0=
Referer: https://refererwebsitetest.html
Content-Length: 61
Cookie: session=eyJpdiI6IkI4XC9ndnFr6UlwvbEZMWhIK1wvbTFRSkE9PSIsInZhbHVlIjoicStyR2c3T240UW41RW5OdEFtcM2NjMjJ2V2d3Q0Yk9cL0tjZEFyV1NwSmpDbmdyc3BGZklva3RhaFJ5SWFCOFdiOHhobE1ySlU3NnJhMXMrckMzeXkxOiI1MjQxMkZuTndnPT0iLCJtYWMiY2VjMDVmiODE4YjI2YzViMjdiYzQ4MTk1ZDllMDVjOGE0MGRkMTFiYWFkNDRlZjM1MGQ4YzZjIn0%3D; XSRF-TOKEN=eyJpdiI6ImxXMHNNQ01RT0RHTEMreU9lc0duZWc9PSIsInZhbHVlIjoiZ08zMFJDaTlZV1h5ZHlVRDBzUkFNNXBlY0ZuTFlCQ2V0SlVpRlpJlwvUE1zN1Vza2F5blhDTStNM2NlM05VNXFZc1IxclNPSHhkNkU5Mmt3PT0iLCJtYWMiOiJmMGQxZTg5YmRlYjNmMzNjMWZlN2ZlM2E5YmE1NzRiMTgyMDQ5NDY1ZGZjNjliMDJlNDA2MGQzMjc3MjU2MzE2In0%3D
Connection: keep-alive
I am really a beginner in C# and would appreciate any help.
Thank you!
Updated code:
async static void PostRequest(string url)
{
//PASS HEADER DATA
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
//Repeat for each header you want
request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
request.Headers.Add("Content-Type", "application/json");
request.Headers.Add("X-XSRF-TOKEN", "eyJpdiI6ImxXMHNNQ01RT0RHTEMreU9lc0duZWc9PSIsInZhbHVlIjoiZ08zMFJDaTlZV1h5ZHlVRDBzUkFNNXBlY0ZuTFlCQ2V0SlVpRlpJRUUrRUl0NlwvUE1zN1Vza2F5blhDTStNM2NlM05VNXFZc1IxclNPSHhkNkU5Mmt3PT0iLCJtYWMiOiJmMGQxZTg5YmRlYjNmMzNjMWZlN2ZlM2E5YmE1NzRiMTgyMDQ5NDY1ZGZjNjliMDJlNDA2MGQzMjc3MjU2MzE2In0=");
request.Headers.Add("Referer", "https://refererwebsitetest.html");
request.Headers.Add("Content-Length", "61");
request.Headers.Add("Cookie", "session=eyJpdiI6IkI4XC9ndnFr6UlwvbEZMWhIK1wvbTFRSkE9PSIsInZhbHVlIjoicStyR2c3T240UW41RW5OdEFtcM2NjMjJ2V2d3Q0Yk9cL0tjZEFyV1NwSmpDbmdyc3BGZklva3RhaFJ5SWFCOFdiOHhobE1ySlU3NnJhMXMrckMzeXkxOiI1MjQxMkZuTndnPT0iLCJtYWMiY2VjMDVmiODE4YjI2YzViMjdiYzQ4MTk1ZDllMDVjOGE0MGRkMTFiYWFkNDRlZjM1MGQ4YzZjIn0%3D; XSRF-TOKEN=eyJpdiI6ImxXMHNNQ01RT0RHTEMreU9lc0duZWc9PSIsInZhbHVlIjoiZ08zMFJDaTlZV1h5ZHlVRDBzUkFNNXBlY0ZuTFlCQ2V0SlVpRlpJlwvUE1zN1Vza2F5blhDTStNM2NlM05VNXFZc1IxclNPSHhkNkU5Mmt3PT0iLCJtYWMiOiJmMGQxZTg5YmRlYjNmMzNjMWZlN2ZlM2E5YmE1NzRiMTgyMDQ5NDY1ZGZjNjliMDJlNDA2MGQzMjc3MjU2MzE2In0%3D");
request.Headers.Add("Connection", "keep-alive");
using (HttpClient client = new HttpClient())
{
await client.SendAsync(request);
}
//POST DATA
IEnumerable<KeyValuePair<string, string>> queries = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("data1": "name"),
new KeyValuePair<string, string>("data2": "555")
};
HttpContent q = new FormUrlEncodedContent(queries);
using (HttpClient client = new HttpClient()) //using for disposing if not in use
{
using (HttpResponseMessage response = await client.PostAsync(url, q)) //url, content in postAsync
{
using (HttpContent content = response.Content) //store content (data) into a 'content'
{
string mycontent = await content.ReadAsStringAsync();
//HttpContentHeaders headers = content.Headers;
Console.WriteLine(mycontent);
}
}
}
}
it comes up with the following errors:
// FIXED
applied the code from Microsoft website:
https://learn.microsoft.com/en-us/dotnet/framework/network-programming/how-to-send-data-using-the-webrequest-class
lastly added headers from your example, THX works!

You can use the HttpRequestMessage class and set the headers you want then send it as a POST using the SendAsync method on the HttpClient.
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
//Repeat for each header you want
request.Headers.Add("headerName","headervalue");
using (HttpClient client = new HttpClient())
{
await client.SendAsync(request);
}

Related

How to convert application/x-www-form-urlencoded to JSON?

I made http post request with content type application/x-www-form-urlencoded UTF-8 using Httpclient.PostRequest. I need to convert application/x-www-form-urlencoded request result to json string. How can I application/x-www-form-urlencoded to json in C#?
I did next post request.
HttpResponseMessage response;
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://sv.ki.court.gov.ua/new.php"))
{
request.Headers.TryAddWithoutValidation("Connection", "keep-alive");
request.Headers.TryAddWithoutValidation("Accept", "application/json, text/javascript, */*; q=0.01");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br");
request.Headers.TryAddWithoutValidation("Accept-Language", "en-US,en;q=0.9");
request.Headers.TryAddWithoutValidation("Referer", "https://sv.ki.court.gov.ua/sud2608/gromadyanam/csz");
request.Headers.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36");
request.Headers.TryAddWithoutValidation("Origin", "https://sv.ki.court.gov.ua");
request.Headers.TryAddWithoutValidation("X-Requested-With", "XMLHttpRequest");
request.Headers.TryAddWithoutValidation("Cookie", "_ga=GA1.3.1754947237.1562858299; PHPSESSID=1nosm5dhdljsv8tpsu97bl8dn5; cookiesession1=257F9822DPOYFGLLUDVTJCMDYYR98AB6; _gid=GA1.3.1599643655.1563891940; _gat=1");
request.Content = new StringContent("q_court_id=2608", Encoding.UTF8, "application/x-www-form-urlencoded");
response = await _client.SendAsync(request);
}
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var json = await response.Content.ReadAsStringAsync();
As StringContent type I used application/x-www-form-urlencoded. application/json doesn't work. Post request return result string "\u001f<....". I need to convert response result application/x-www-form-urlencoded to application/json
This should give you some idea. In the example below inside PostAsync you pass in a new instance of StringContent where you set the type of content i.e. in this case Json.
public static async Task MainAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:1234");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("", "Joe Bloggs")
});
var result = await client.PostAsync("/api/Customer/exists", new StringContent(content.ToString(), Encoding.UTF8, "application/json"));
string resultContent = await result.Content.ReadAsStringAsync();
Console.WriteLine(resultContent);
}
}

Calling SharePoint with HttpClient PostAsync() results into forbidden response

I am trying to send HttpClient PostAsync() request to company's internal sharepoint site but its returning response with forbidden error. I have all necessary access permission for site to load and have also passed required headers to the HttpClient object.
Here is code snippet.
HttpClient client = new System.Net.Http.HttpClient (new HttpClientHandler { UseDefaultCredentials = true });
client.BaseAddress = new Uri (string.Format (API_URL, p_siteNumber));
client.DefaultRequestHeaders.Accept.Add (new MediaTypeWithQualityHeaderValue (#"application/atom+xml"));
client.DefaultRequestHeaders.TryAddWithoutValidation ("Accept-Encoding", "gzip, deflate");
client.DefaultRequestHeaders.TryAddWithoutValidation ("Accept-Language", "en-US, en;q=0.8, hi;q=0.6");
client.DefaultRequestHeaders.TryAddWithoutValidation ("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
client.DefaultRequestHeaders.TryAddWithoutValidation ("Accept-Charset", "ISO-8859-1");
HttpResponseMessage httpResponse = await client.PostAsync (urlHttpPost, new StringContent (string.Empty));
string response = await httpResponse.Content.ReadAsStringAsync ();
Can anyone help me with this?
Thanks in advance.
I ran into the same problem I wanted to send the file and some string contents with it.
so below code helped me!!
using (var client = new HttpClient())
{
//client.DefaultRequestHeaders.Add("User-Agent", "CBS Brightcove API Service");
string authorization = GenerateBase64();
client.DefaultRequestHeaders.Add("Authorization", authorization);
using (var content = new MultipartFormDataContent())
{
string fileName = Path.GetFileName(textBox1.Text);
//Content-Disposition: form-data; name="json"
var stringContent = new StringContent(InstancePropertyObject);
stringContent.Headers.Remove("Content-Type");
stringContent.Headers.Add("Content-Type", "application/json");
stringContent.Headers.Add("Content-Disposition", "form-data; name=\"instance\"");
content.Add(stringContent, "instance");
var fileContent = new ByteArrayContent(filecontent);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
content.Add(fileContent);
var result = client.PostAsync(targetURL, content).Result;
}
}

Forcing HttpClient to use Content-Type: text/xml

This is driving me nuts, I am setting the ContentType header everywhere I can and can't seem to make it stop sending text/plain.
Watching the data in Fiddler, the request is always requesting:
POST http:/domain.com HTTP/1.1
Content-Type: text/plain; charset=utf-8
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, "http://domain.com");
request.Content = new StringContent(Serialize(obj), Encoding.UTF8, "text/xml");
request.Content.Headers.Clear();
request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
request.Headers.Clear();
request.Headers.Add("Content-Type","text/xml");
var response = await httpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
It looks like you tried to hard :) This should just work.
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, "http://domain.com");
request.Content = new StringContent(Serialize(obj), Encoding.UTF8, "text/xml");
var response = await httpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
Try settings the default request headers:
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
Use "application/xml" instead of "text/xml"

json parameter to request on Windows 8 (RT)

I'm looking for solution to send request with JSON like parameter to server.
I use this code,
var httpClient = new HttpClient();
var tempByteArray = Encoding.UTF8.GetBytes("my valid json");
var stream = new MemoryStream(tempByteArray);
var streamContent = new StreamContent(stream);
var request = new HttpRequestMessage(HttpMethod.Post, Constants.LocalServer);
request.Content = streamContent;
request.Headers.TransferEncodingChunked = true;
HttpResponseMessage response = await httpClient.SendAsync(request);
But in response I get:
{
StatusCode: 501,
ReasonPhrase: 'NotImplemented',
Version: 1.0,
Content: System.Net.Http.StreamContent,
Headers: {
X-Squid-Error: ERR_UNSUP_REQ0X-Cache: MISSfromproxy3.itos.orgX-Cache-Lookup: NONEfromproxy3.companyname.org: portProxy-Connection: closeDate: Thu,
18Apr201309: 17: 53GMTServer: squid/2.6.STABLE21Via: 1.0proxy3.companyname.org: port(squid/2.6.STABLE21)Content-Length: 1099Content-Type: text/htmlExpires: Thu,
18Apr201309: 17: 53GMT
}
}
May be have another way to sent request with json parameter on Win8?
UPDATE I found solution:
public static async Task<string> LoadData(string json, string serverUrl)
{
var request = (HttpWebRequest)WebRequest.Create(new Uri(Constants.LocalServer));
request.ContentType = "application/json";
request.Method = "POST";
using (var requestStream = await request.GetRequestStreamAsync())
{
var writer = new StreamWriter(requestStream);
writer.Write(json);
writer.Flush();
}
using (var resp = await request.GetResponseAsync())
{
using (var responseStream = resp.GetResponseStream())
{
var reader = new StreamReader(responseStream);
return = reader.ReadToEnd();
}
}
}
It's work great, but must exists more simple way(i hope). And I'll try to find it.
When I post data using your two code snippets, I see some differences in the requests.
Here is the raw post for the first code sample (that you say does not work):
POST http://testing.foo.com/api/Values HTTP/1.1
Host: testing.foo.com
Expect: 100-continue
Connection: Keep-Alive
Content-Length: 75
{
id:"1",
title:"title text",
post:"post text",
isDeleted:"False"
}
This is the raw post for the code in your update (code that you say works):
POST http://testing.foo.com/api/Values HTTP/1.1
Content-Type: application/json
Host: testing.foo.com
Content-Length: 75
Expect: 100-continue
{
id:"2",
title:"title text",
post:"post text",
isDeleted:"False"
}
The differences in the two requests are as follows:
In the first request, the content type is never set.
In the first request, the content is UTF8 encoded.
To fix your non-working code, I would suggest you try one or both of the following:
Set the content type to application/json
Not UTF8 encode the request
At that moment this solution is most useful.
public static async Task<string> LoadData(string json, string serverUrl)
{
var request = (HttpWebRequest)WebRequest.Create(new Uri(Constants.LocalServer));
request.ContentType = "application/json";
request.Method = "POST";
using (var requestStream = await request.GetRequestStreamAsync())
{
var writer = new StreamWriter(requestStream);
writer.Write(json);
writer.Flush();
}
using (var resp = await request.GetResponseAsync())
{
using (var responseStream = resp.GetResponseStream())
{
var reader = new StreamReader(responseStream);
return = reader.ReadToEnd();
}
}
}

Api POST from code behind

I want to post an object using an API call. I'm getting the data using the following code in my codebehind
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["JUri"]);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/receipt/" + jID).Result;
if (response.IsSuccessStatusCode)
{}
I would like to know there is any code equivalent to POST for this.
POST using Form:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["JUri"]);
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("Key1", "Value1"));
postData.Add(new KeyValuePair<string, string>("Key2 ", "Value2"));
HttpContent content = new FormUrlEncodedContent(postData);
var response = client.PostAsync("api/receipt/" + jID, content)
if (response.IsSuccessStatusCode)
{}
POST using JSON, assume you have Dto class:
var client = new HttpClient();
var dto = new Dto {Pro1 = "abc"};
var reponse = client.PostAsJsonAsync("api/receipt/" + jID, dto).Result;
if (reponse.IsSuccessStatusCode)
{}
The best way for you is to use a third-party library, like RestSharp
The simple way to post something to your api via RestSharp will look like that:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
using RestSharp;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
public class SimpleConnector
{
private CookieContainer _cookieJar = new CookieContainer();
private RestClient client = new RestClient();
public string TwitterAuthenticate(string user, string pass)
{
client.CookieContainer = _cookieJar;
//RestClient client = new RestClient("https://twitter.com");
IRestRequest request = new RestRequest("https://twitter.com/", Method.GET);
client.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0";
client.AddDefaultHeader("Accept", "*/*");
//request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
//request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
// easily add HTTP Headers
//request.AddHeader("header", "value");
// add files to upload (works with compatible verbs)
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content;
Match m = Regex.Match(content, #"name=""authenticity_token""\s*value=""(.*?)"">");
string authenticity_token = m.Groups[1].Value;
request = new RestRequest("https://twitter.com/sessions", Method.POST);
request.AddParameter("session[username_or_email]", user);
request.AddParameter("session[password]", pass);
request.AddParameter("return_to_ssl", "true");
request.AddParameter("scribe_log", "");
request.AddParameter("redirect_after_login", "/");
request.AddParameter("authenticity_token", authenticity_token);
response = client.Execute(request);
content = response.Content;
return content;
}
Yes, you can do this way:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["JUri"]);
You could either use one of these methods as given below as per your requirement:
Task<HttpResponseMessage> response = client.PostAsJsonAsync();
OR
Task<HttpResponseMessage> response = client.PostAsXmlAsync();
OR
Task<HttpResponseMessage> response = client.PostAsync();
Hope this helps!

Categories

Resources