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"));
.....
}
Related
Using RESTSharp, I am able to login:
RestClient client = new RestClient(Constants.APIURL + "method/login");
CookieContainer cookieJar = new CookieContainer();
RestRequest request = new RestRequest(Method.POST);
client.CookieContainer = cookieJar;
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
request.AddJsonBody(new
{
usr = username,
pwd = password
});
var response = client.Execute(request);
var cookie = HttpContext.Current.Server.UrlDecode(response.Headers.ToList().Find(x => x.Name == "Set-Cookie").Value.ToString());
I am then storing the cookies and sending to another API call, also through RESTSharp.
RestClient client = new RestClient(Constants.APIURL);
RestRequest request = new RestRequest("resource/Asset", Method.GET);
request.AddCookie("Cookie", HttpContext.Current.Server.UrlEncode(cookie));
But it keeps returning 403 forbidden. I tried on POSTMan, it works absolutely fine.
Any help? Is it that I am sending the cookies wrongly? I tried sending the cookies in a HttpWebRequest and it is working absolutely fine.
I also tried copy pasting a code generated from Postman where cookie was passed in a header but it didn't work. I tried sending cookie as below and it worked
client.AddDefaultHeader("Cookie", cookie);
235 / 5.000
Resultados de traducción
For RestSharp v107 and >
You can use CookieContainer and in it store all received Cookies.
then pass the CookieContainer to RestClientOptions and use it as a parameter when instantiating var client1 = new RestClient(options);
CookieContainer cookieJar = new CookieContainer();
cookieJar.Add(response.Cookies);
var options1 = new RestClientOptions(UL.moodle_host + "login/index.php?")
{
ThrowOnAnyError = true,
UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0",
FollowRedirects = true,
CookieContainer = cookieJar
};
// new request TRY loging
var client1 = new RestClient(options1);
I'm having a little problem. Why is that I'm getting internal 500 error on Visual Studio?
But on Visual Studio Code I don't getting any error and I successfully getting the token.
Here's my current code. Could you tell me where is my error? because I can't find the error even if I do a debugging.
private static string loginUrl = "https://site.tv/user/login";
private static string RequestVerificationToken { get; set; } = "y5cc9W5WNIdQnNVrkmNlwu0IdyaMs8p3mWFDlkK2S3ns_xTX7lH2j6YMec0MFnOItl_t7bgKEtFgOQJQ2CGluYdZdOE1";
private static string BodyVerificationToken { get; set; } = "1b0lTOz_7zBnqHTAw6-K0YATOUUcMfYXXYCPJadz0L5XyDNYPBY832N9UEAWYIKlLpj69XdlD34dBhqNw3BnqhQVVpU1";
private static readonly CookieContainer cookieContainer = new CookieContainer();
private static readonly HttpClientHandler handler = new HttpClientHandler
{
CookieContainer = cookieContainer,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
UseCookies = true,
UseProxy = false,
Proxy = null
};
private static readonly HttpClient client = new HttpClient(handler);
public static async Task<string> Login(string username, string password)
{
var random = RandomHexDigits();
var boundary = "------WebKitFormBoundary" + random;
var body = MakeMultipartForm(boundary, new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("__requestverificationtoken", BodyVerificationToken),
new KeyValuePair<string, string>("logintype", "email"),
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password)
});
Uri uri = new Uri(loginUrl, UriKind.RelativeOrAbsolute);
using (var request = new HttpRequestMessage(HttpMethod.Post,uri))
{
using (var content = new StringContent(body, Encoding.UTF8, "multipart/form-data"))
{
content.Headers.Remove("Content-Type");
content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("multipart/form-data");
content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("boundary", $"----WebKitFormBoundary{random}"));
byte[] postBytes = Encoding.UTF8.GetBytes(body);
content.Headers.ContentLength = postBytes.Length;
request.Content = content;
return await ResponseMessage(request);
}
}
}
private static async Task<string> ResponseMessage(HttpRequestMessage request)
{
request.Headers.Accept.Clear();
request.Headers.Add("Accept-Language", "en-US,en;q=0.5");
request.Headers.Add("Accept-Encoding", "gzip, deflate");
request.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
request.Headers.UserAgent.TryParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36");
request.Headers.CacheControl = new CacheControlHeaderValue { MaxAge = new TimeSpan(0), NoCache = true };
request.Headers.TryAddWithoutValidation("Origin", "https://site.tv");
request.Headers.TryAddWithoutValidation("Sec-Fetch-Site", "same-origin");
request.Headers.TryAddWithoutValidation("Sec-Fetch-Mode", "navigate");
request.Headers.TryAddWithoutValidation("Sec-Fetch-User", "?1");
request.Headers.TryAddWithoutValidation("Sec-Fetch-Dest", "document");
request.Headers.Referrer = new Uri("https://site.tv/");
request.Headers.Host = "site.tv";
request.Headers.Add("Cookie", $"__RequestVerificationToken={RequestVerificationToken}");
request.Headers.Add("Connection", "keep-alive");
using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false))
{
if (!response.IsSuccessStatusCode) { throw new Exception(); }
return GetCookie(loginUrl, ".GNSAUTH");
}
}
UPDATE: I see this error when I read the html from the response.
the required anti-forgery cookie __requestverificationtoken is not present
I already fixed it.
Instead of setting the cookie from the request:
request.Headers.Add("Cookie", $"__RequestVerificationToken={RequestVerificationToken}");
I just set the cookie to like this and it solved my problem.
cookieContainer.Add(uri, new Cookie("__RequestVerificationToken", RequestVerificationToken));
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);
}
}
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;
}
}
I'm having trouble making POST using http client with Accept, ContentType and Authentication as headers. I tried several implementations using send aysnc and post async and all seemed to fail. I used https://www.hurl.it/ to make sure if it also was getting a time out error but it is working, getting back json data.
I get a connection time out error exception (in: var response = await client.SendAsync(request);) when running the below code.
Also I have curl command which i was trying to go off by, which is listed below as well.
Implementation:
// Body
var dictionary = new Dictionary<string, string>();
dictionary.Add("id", "123");
var formData = new List<KeyValuePair<string, string>>();
formData.Add(new KeyValuePair<string, string>("id", "123"));
// Http Client
var client = new HttpClient();
client.BaseAddress = new Uri("https://www.some_website.com/api/house");
// Http Request
var request = new HttpRequestMessage(HttpMethod.Post, "https://www.some_website.com/api/house");
// Accept
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Content-Type
//request.Content = new FormUrlEncodedContent(dictionary);
var httpContent = new StringContent(
JsonConvert.SerializeObject(
dictionary,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}),
Encoding.UTF8,
"application/json");
request.Content = new StringContent(
JsonConvert.SerializeObject(
dictionary,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}),
Encoding.UTF8,
"application/json");
// Authentication
var byteArray = new UTF8Encoding().GetBytes("user" + ":" + "pass");
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
client.DefaultRequestHeaders.Authorization = header;
// Communication
try
{
var response = await client.SendAsync(request);//PostAsync("https://www.some_website.com/api/house", httpContent);
if (response.IsSuccessStatusCode)
{
var myContent = await response.Content.ReadAsStringAsync();
var deliveryStatus = JsonConvert.DeserializeObject<MyOjbect>(myContent);
}
}
catch (Exception e)
{
//catch error
}
Curl:
curl -i --user user:123 -H Accept:application/json -H content-type:application/json -H cache-control:no-cache -X POST https://www.some_website.com/api/house -H Content-Type: application/json -d '{"id": "123"}'
You set your BaseAddress and the HttpRequestMessage Uri property both to the same absolute url, shouldn't it be the base address (ex. somewebsite.com) and the relative url (ex. (api/house). You can also inspect your request with Fiddler telerik.com/fiddler