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);
}
}
Related
so I have this website
After inspecting the network traffic for the download button I got the below curl post request
curl "https://flood-map-for-planning.service.gov.uk/pdf" -X POST -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:104.0) Gecko/20100101 Firefox/104.0" -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8" -H "Accept-Language: en-US,en;q=0.5" -H "Accept-Encoding: gzip, deflate, br" -H "Content-Type: application/x-www-form-urlencoded" -H "Origin: https://flood-map-for-planning.service.gov.uk" -H "Connection: keep-alive" -H "Referer: https://flood-map-for-planning.service.gov.uk/flood-zone-results?easting=429240&northing=431613&location=LS118TR" -H "Upgrade-Insecure-Requests: 1" -H "Sec-Fetch-Dest: document" -H "Sec-Fetch-Mode: navigate" -H "Sec-Fetch-Site: same-origin" -H "Sec-Fetch-User: ?1" -H "TE: trailers" --data-raw "id=1660136366038&polygon=¢er="%"5B429240"%"2C431613"%"5D&reference=&scale=2500"
I went over to this website in order to convert the curl to c#
This is what I got
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://flood-map-for-planning.service.gov.uk/pdf"))
{
request.Headers.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:104.0) Gecko/20100101 Firefox/104.0");
request.Headers.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8");
request.Headers.TryAddWithoutValidation("Accept-Language", "en-US,en;q=0.5");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br");
request.Headers.TryAddWithoutValidation("Origin", "https://flood-map-for-planning.service.gov.uk");
request.Headers.TryAddWithoutValidation("Connection", "keep-alive");
request.Headers.TryAddWithoutValidation("Referer", "https://flood-map-for-planning.service.gov.uk/flood-zone-results?easting=429240&northing=431613&location=LS118TR");
request.Headers.TryAddWithoutValidation("Upgrade-Insecure-Requests", "1");
request.Headers.TryAddWithoutValidation("Sec-Fetch-Dest", "document");
request.Headers.TryAddWithoutValidation("Sec-Fetch-Mode", "navigate");
request.Headers.TryAddWithoutValidation("Sec-Fetch-Site", "same-origin");
request.Headers.TryAddWithoutValidation("Sec-Fetch-User", "?1");
request.Headers.TryAddWithoutValidation("TE", "trailers");
request.Content = new StringContent("id=1660136366038&polygon=¢er=");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = await httpClient.SendAsync(request);
}
}
I changed it to:
var httpClient = new HttpClient();
var request =
new HttpRequestMessage(new HttpMethod("POST"), "https://flood-map-for-planning.service.gov.uk/pdf");
request.Headers.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:104.0) Gecko/20100101 Firefox/104.0");
request.Headers.TryAddWithoutValidation("Accept", "application/pdf");
request.Headers.TryAddWithoutValidation("Accept-Language", "en-US,en;q=0.5");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br");
request.Headers.TryAddWithoutValidation("Origin", "https://flood-map-for-planning.service.gov.uk");
request.Headers.TryAddWithoutValidation("Connection", "keep-alive");
request.Headers.TryAddWithoutValidation("Referer", "https://flood-map-for-planning.service.gov.uk/flood-zone-results?easting=429240&northing=431613&location=LS118TR");
request.Headers.TryAddWithoutValidation("Upgrade-Insecure-Requests", "1");
request.Headers.TryAddWithoutValidation("Sec-Fetch-Dest", "document");
request.Headers.TryAddWithoutValidation("Sec-Fetch-Mode", "navigate");
request.Headers.TryAddWithoutValidation("Sec-Fetch-Site", "same-origin");
request.Headers.TryAddWithoutValidation("Sec-Fetch-User", "?1");
request.Headers.TryAddWithoutValidation("TE", "trailers");
request.Content = new StringContent("center=&scale=2500");
var response = httpClient.Send(request);
response.Content.Headers.Add("Content-Disposition", "inline;filename=\"Testpdf.pdf\"");
response.Content.Headers.Add("Content-Name", "Testpdf.PDF");
response.Content.Headers.Add("Content-Type", "application/pdf;charset=UTF-8");
if (response.IsSuccessStatusCode)
{
using (FileStream fs = new FileStream("somepdf.pdf", FileMode.CreateNew))
{
using (StreamWriter writer = new StreamWriter(fs))
{
var contentStream = response.Content.ReadAsStream(); // get the actual content stream
writer.Write(contentStream);
}
}
}
This is the issue.
My goal is to download the pdf locally.
I usually get a file which is 1KB or 6KB.
The curl command with an output parameter works without an issue. I'm just not sure what the above c# http post request is missing.
As you can see I've added the filestream and streamwriter usages.
I've also tried to play with the response in order to nagivate it to an application/pdf response.
Any ideas why I am doing wrong?
=======================================================
EDIT
Thanks to #thehennyy,
here is the working solution:
var unixTimestamp = (long)DateTime.UtcNow.Subtract(DateTime.UnixEpoch).TotalSeconds;
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
using (var httpClient = new HttpClient(handler))
{
using (var request =
new HttpRequestMessage(new HttpMethod("POST"), "https://flood-map-for-planning.service.gov.uk/pdf"))
{
request.Headers.TryAddWithoutValidation("Referer",
"https://flood-map-for-planning.service.gov.uk/flood-zone-results?easting=429240&northing=431613&location=LS118TR");
request.Content =
new StringContent($"id={unixTimestamp}&polygon=¢er=[429240,431613]&reference=&scale=2500");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
using (FileStream fs = new FileStream("somepdf.pdf", FileMode.Create))
{
var contentStream = await response.Content.ReadAsStreamAsync();
await contentStream.CopyToAsync(fs);
}
}
}
}
There are a few things to consider here:
It seems like the curl to httpclient converter had a problem converting the post content. The following works for me:
request.Content = new StringContent("id=1&polygon=¢er=[429240,431613]&reference=&scale=2500");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
The parameter id has to be provided, otherwise the request will fail. The website uses the current unix timestamp as value for the id parameter.
Adding headers to the response response.Content.Headers.Add([...]) is not meaningful, just delete these lines.
Writing the content to disk can be done simpler:
using (FileStream fs = new FileStream("somepdf.pdf", FileMode.Create))
{
var contentStream = await response.Content.ReadAsStreamAsync();
await contentStream.CopyToAsync(fs);
}
While testing i got the same "wrong" files, these are usual just html responses, sometimes containing an error message. View them as html. Maybe they seem like gibberish, then you have to turn on automatic decompression:
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
var httpClient = new HttpClient(handler);
The automatic decompression values should match this headers values:
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
Current versions of dotnet also support "br" - DecompressionMethods.Brotli.
Using automatic decompression is helpful in nearly every case.
I am trying post api through HTTP client in C#, For authorization ,we send Bearer token.
But it is not getting inserted in the client side. It throws an error.
My code here:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
string result = "";
using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
{
client.BaseAddress = new Uri(baseURL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Cookie", "ebpPermHash=-396055074);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + authtoken);
client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
client.DefaultRequestHeaders.Add("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8");
client.DefaultRequestHeaders.Add("Cache-Control", "no-cache")
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
HttpResponseMessage response = client.PostAsJsonAsync("/v2/bb/sa", payModel).Result;
var responseString = response.Content.ReadAsStringAsync();
result = responseString.Result;
dynamic data = JObject.Parse(result);
string throwresult = Convert.ToString(data);
result = data.authToken;
logErr.ControlLog(throwresult);
}
return result;
But I am getting error like:
exceptionType": "com.ebpsource.exception.AuthenticationFailedException",
"name": "AUTHENTICATION_REQUIRED",
"message": "Authentication is required to call 'Resource.execute'",
"address": "/service/Resource.execute",
"httpRequestBody": {
"header": {
"config": {
"action": "insert",
"resourceName": "sa"
}
Thanks in advance.
I suggest you check your backend with Postman first, to verify if it is a backend issue or a client issue
you have a bug, a wrong syntax to add a token. And plus to many headers. Try this
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
client.BaseAddress = new Uri(baseAddress);
var jsonData = JsonConvert.SerializeObject(payModel);
var contentData = new StringContent(jsonData, Encoding.UTF8, "application/json");
var response = client.PostAsync("/v2/bb/sa", contentData).Result;
if (response.IsSuccessStatusCode)
{
var stringData = response.Content.ReadAsStringAsync().Result;
var result = JsonConvert.DeserializeObject<object>(stringData);
}
}
UPDATE
if you need to add cookies you can do it this way
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler))
{
....
cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
.....
}
I have to send ajax request from C#. In browser the request looks like:
Request URL:https://sts-service.mycompany.com/UPNFromUserName
Request method:POST
Remote address:xxxx
Status code:
200
Version:HTTP/2.0
Referrer Policy:strict-origin-when-cross-origin
Headers:
Host: sts-service.mycompany.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: https://sts.mycompany.com/
Content-type: application/x-www-form-urlencoded
Content-Length: 17
Origin: https://sts.mycompany.com
DNT: 1
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Params:
Form data:
MS.Aution
Cookies: no cookie
And in C# my request:
WebRequest webRequest = WebRequest.Create("https://sts-service.mycompany.com/UPNFromUserName");
((HttpWebRequest)webRequest).Referer = "https://sts.mycompany.com/";
((HttpWebRequest)webRequest).Host = "sts-service.mycompany.com";
((HttpWebRequest)webRequest).KeepAlive = true;
((HttpWebRequest)webRequest).AllowAutoRedirect = true;
((HttpWebRequest)webRequest).UseDefaultCredentials = true;
((HttpWebRequest)webRequest).UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0";
webRequest.ContentType = "application/x-www-form-urlencoded";
((HttpWebRequest)webRequest).Accept = "*/*";
((HttpWebRequest)webRequest).Headers.Add("Origin", "https://sts.mycompany.com");
((HttpWebRequest)webRequest).Headers.Add("Accept-Encoding", "gzip, deflate, br");
((HttpWebRequest)webRequest).Headers.Add("Accept-Language", "en-US,en;q=0.5");
((HttpWebRequest)webRequest).Headers.Add("Upgrade-Insecure-Requests", #"1");
((HttpWebRequest)webRequest).Headers.Add("DNT", #"1");
((HttpWebRequest)webRequest).AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
webRequest.Method = HttpRequestType.POST.ToString();
string msg = "MSCnE.Automation";
webRequest.ContentLength = msg.Length;
Stream reqStream = webRequest.GetRequestStream();
byte[] msgb = System.Text.Encoding.UTF8.GetBytes(msg);
reqStream.Write(msgb, 0, msgb.Length);
reqStream.Close();
var response = (HttpWebResponse)webRequest.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string Result = sr.ReadToEnd();
response.Close();
I get error:
The remote server returned an error: (400) Bad Request.
In browser in Network tab the request looks like:
Type is json but in Headers Content Type is application/x-www-form-urlencoded
Maybe this is the reason?
something along these lines (not tested):
public async Task<string> SendPOST()
{
var dict = new Dictionary<string, string>();
dict.Add("DNT", "1");
dict.Add("someformdata","MSCnE.Automation");
using (var formdata = new System.Net.Http.FormUrlEncodedContent(dict))
{
//do not use using HttpClient() - https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient
using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
{
formdata.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
formdata.Headers.ContentType.CharSet = "UTF-8";
httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0");
using (var response = await httpClient.PostAsync("https://sts-service.mycompany.com/UPNFromUserName", formdata))
{
if (response.IsSuccessStatusCode)
{
var postresult = await response.Content.ReadAsStringAsync();
return postresult;
}
else
{
string errorresult = await response.Content.ReadAsStringAsync();
return errorresult;
}
}
}
}
}
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);
}
My current job is to consume a RESTful API with OAuth2. Currently I worked out how to get the access token and it is working ok while I use the chrome extension Rest Console, but when I try to do it from my application I always get the error that I am sending an invalid OAuth request. Below you can see three of the ways I tried to consume the API, but to no success. The page always returns error 500. Any help will be appreciated, if I had missed something crucial.
var auth = "Bearer " + item.access_token;
/* First Attempt */
var client = new RestClient("http://<link>");
var request = new RestRequest("sample", Method.GET);
request.AddHeader("Authorization", auth);
request.AddHeader("Content-Type", "application/json;charset=UTF-8");
request.AddHeader("Pragma", "no-cache");
request.AddHeader("User-Agent", "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
request.AddHeader("Accept", "application/json");
request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
var content = response.Content;
/* Second Attempt */
string sURL = "http://<link>/sample";
string result = "";
using (WebClient client = new WebClient())
{
client.Headers["Authorization"] = auth;
client.Headers["Content-Type"] = "application/json;charset=UTF-8";
client.Headers["Pragma"] = "no-cache";
client.Headers["User-Agent"] = "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
client.Headers["Accept"] = "application/json";
byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
var result1 = client.DownloadString(sURL);
}
/* Third Attempt */
var request = (HttpWebRequest)WebRequest.Create(sURL);
request.Method = "GET";
request.ContentType = "application/json;charset=UTF-8";
request.Accept = "application/json";
request.Headers["Authorization"] = auth;
request.UserAgent = "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
string content;
HttpStatusCode statusCode;
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
var contentType = response.ContentType;
Encoding encoding = null;
if (contentType != null)
{
var match = Regex.Match(contentType, #"(?<=charset\=).*");
if (match.Success)
encoding = Encoding.GetEncoding(match.ToString());
}
encoding = encoding ?? Encoding.UTF8;
statusCode = ((HttpWebResponse)response).StatusCode;
using (var reader = new StreamReader(stream, encoding))
content = reader.ReadToEnd();
}
--------EDIT--------
For the first attempt I also tried to add the authentication to the client variable client.Authenticator = Authenticate; where OAuth2AuthorizationRequestHeaderAuthenticator Authenticate = new OAuth2AuthorizationRequestHeaderAuthenticator(item.access_token, item.token_type);
The code seems right. The fail attempts you did suggest that the issue is with the token and not the code. Bearer tokens have expiration time. So semms like your token expired between the first time you got it using chrome REST Console extension and when you wrote your code. But the strange situation here is the 500 error code you got. 401 is standard response when you token expired or not exist. 500 error code always mean server error.