I got an issue with the HttpResponsemessage process, everything works for the sending request but during the readin of the responce i've got an error
InvalidOperationException : The character set provided in ContentType is invalid.
using (var handler = new HttpClientHandler())
{
if (handler.SupportsAutomaticDecompression)
{
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
using (var client = new HttpClient(handler) { BaseAddress = new Uri(BaseAddress) })
{
Dictionary<string, string> dico = new Dictionary<string, string>();
dico.Add("username", _username);
dico.Add("password", _password);
HttpResponseMessage response = client.PostAsync("/auth", new FormUrlEncodedContent(dico)).Result;
var tokResult = response.Content.ReadAsStringAsync().Result;
var tokObj = JsonConvert.DeserializeObject<AuthResult>(tokResult);
string token = tokObj.Token;
return token;
}
}
header values of the response :
{StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:{ Connection: keep-alive Server: cloudflare-nginx Transfer-Encoding: chunked CF-RAY: 35e6bfcc8f3c3c77-CDG T411-node: webus1 Set-Cookie: __cfduid=db2de200ea64f72bef261054785e1047c1494690372; expires=Sun, 13-May-18 15:46:12 GMT; path=/; domain=.t411.al; HttpOnly Date: Sat, 13 May 2017 15:46:12 GMT X-Powered-By: PHP/5.5.38-4+deb.sury.org~xenial+1 Content-Type: text/html; charset=windows-1252}}
The solution I found is :
var request = (HttpWebRequest)WebRequest.Create(BaseAddress + "/auth");
var postData = "username=" + _username ;
postData += "&password=" + _password;
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var stream = request.GetRequestStreamAsync().Result)
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponseAsync().Result;
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
var tokObj = JsonConvert.DeserializeObject<AuthResult>(responseString);
string token = tokObj.Token;
return token;
Related
I am working with Nasdaq Fund Network Data Service first time. i am calling their one of the API where passing user id,pwd and access key but always getting 401 status code. i am not able to figure out what is wrong in my http call. please some one have a look at the code and tell me where i made the mistake for which i am getting 401 status code instead of right response.
here is my sample code where i could not share actual credentials and access key.
giving the code
string url = "sample url";
Uri u = new Uri(url);
string username = "test1";
string password = "test2";
string accessKey = "myaccesskey";
var payload = new Dictionary<string, string>
{
{"username", username},
{"password", password},
{ "accessKey", accessKey}
};
string strPayload = JsonConvert.SerializeObject(payload);
//HttpContent c = new StringContent(strPayload, Encoding.UTF8, "application/json");
HttpContent c = new StringContent(strPayload, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = string.Empty;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
using (var client = new HttpClient())
{
HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = u,
Content = c
};
var result = client.SendAsync(request).Result;
if (result.IsSuccessStatusCode)
{
response = result.StatusCode.ToString();
}
}
This Error i am getting
{StatusCode: 401, ReasonPhrase: 'Check Username/Password or Access
Key', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: {
Pragma: no-cache X-Frame-Options: SAMEORIGIN Cache-Control:
no-cache Date: Wed, 10 Aug 2022 11:55:36 GMT Content-Length: 0
Expires: -1 }}
Try the following in order to extract the JWT token you receive as a response.
var url = "https://nfn.nasdaq.com/servicecall/tempsession";
var formDataDictionary = new Dictionary<string, string>
{
{ "username", "test1"},
{ "password", "test2"},
{ "accessKey", "myaccesskey"}
};
var formData = new FormUrlEncodedContent(formDataDictionary);
using (var client = new HttpClient())
{
var response = await client.PostAsync(url, formData);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync();
var responseBody = JObject.Parse(result);
var accessToken = responseBody["data']"].Value<string>();
}
ScreenShot
i am getting this error in c# code StatusCode: 415, ReasonPhrase: 'Unsupported Media Type'.
but in postman i am getting a status code 200 OK.
public static void RunPostAsync(FindStaffModel inputs, string token)
{
HttpClient client = new HttpClient();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
client.BaseAddress = new Uri("https://api..................Enquiry");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string json = JsonConvert.SerializeObject(inputs, Formatting.Indented);
var buffer = System.Text.Encoding.UTF8.GetBytes(json);
var byteContent = new ByteArrayContent(buffer);
var httpResponce = new HttpResponseMessage();
try
{
httpResponce = client.PostAsync("https://api..................Enquiry", byteContent).Result;
using (HttpContent contents = httpResponce.Content)
{
var result = contents.ReadAsByteArrayAsync().Result;
var res = (System.Text.Encoding.UTF8.GetString(result));
Console.WriteLine("result :" + res);
}
}
catch (Exception ex)
{
Console.WriteLine("error" + ex);
//Console.WriteLine("respose" + httpResponce);
}
}
i also try this code but i am getting same error
StatusCode: 415, ReasonPhrase: 'Unsupported Media Type', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Cache-Control: no-cache
Pragma: no-cache
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 06 Apr 2020 16:42:33 GMT
Expires: -1
Content-Length: 0
}}
public static void RunPostAsync(FindStaffModel inputs, string token)
{
using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
{
using (var client = new HttpClient(handler) { BaseAddress = new Uri("https://api..................Enquiry") })
{
//add parameters on request
var body = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("FirstName", "test"),
new KeyValuePair<string, string>("LastName", "test"),
new KeyValuePair<string, string>("JobTitleId", "1"),
new KeyValuePair<string, string>("JobTitle", ".Net Developer"),
new KeyValuePair<string, string>("JobTypeId", "2"),
new KeyValuePair<string, string>("JobType", "Part Time") . . . . . . . .
};
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://api...............Enquiry");
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded; charset=UTF-8"));
client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
client.DefaultRequestHeaders.Add("X-MicrosoftAjax", "Delta=true");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
client.Timeout = TimeSpan.FromMilliseconds(10000);
var res = client.PostAsync("https://api.........Enquiry", new FormUrlEncodedContent(body)).Result;
}
}
}
I'm trying to get the data from the website programatically using c# httpclient, but i'm unable to fetch the data.
I have provided the link below
https://ngodarpan.gov.in/index.php/home/statewise_ngo/5972/33/1
there will be a list of data shown in the table format, if you click on the any of the link there will be a popup with a full set of details, which i require to get it programatically for each record.
I have tried generating the csrf_token everytime by hitting the below link
https://ngodarpan.gov.in/index.php/ajaxcontroller/get_csrf
and try to pass the csrf token & id to the following link
https://ngodarpan.gov.in/index.php/ajaxcontroller/show_ngo_info
but this throws an error 403 forbidden.
private void sample1()
{
string str =
"https://ngodarpan.gov.in/index.php/ajaxcontroller/show_ngo_info";
var client = new HttpClient();
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("id", "169486"),
new KeyValuePair<string, string>("csrf_cookie_name",
"decab99c17a84a9040a03c362317289c")
};
var content = new FormUrlEncodedContent(pairs);
var response = client.PostAsync(str, content).Result;
}
{StatusCode: 403, ReasonPhrase: 'Forbidden', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Date: Sun, 09 Jun 2019 07:01:09 GMT
Set-Cookie: csrf_cookie_name=2e39ed6c9bb142836d81233ba1a94732; expires=Sun, 09-Jun-2019 07:01:11 GMT; Max-Age=2; path=/; httponly
Server: Apache/2.4.6
Server: (Red Hat Enterprise Linux)
Server: OpenSSL/1.0.1e-fips
Server: mod_fcgid/2.3.9
Server: PHP/5.6.30
Server: mod_wsgi/3.4
Server: Python/2.7.5
X-Powered-By: PHP/5.6.30
Content-Length: 1131
Content-Type: text/html; charset=UTF-8
}}
when you get csrf_token you should set its value to two things. csrf_test_name in request body and csrf_cookie_name in cookies. you can see network tab details in browser for more details.
private async Task sample1()
{
var url = "https://ngodarpan.gov.in";
var uri = new Uri(url);
string str = $"{url}/index.php/ajaxcontroller/show_ngo_info";
var csrf_token = "80c719c60ac281c34f2f7720fbd28be9";
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = new CookieContainer();
handler.CookieContainer.Add(uri, new Cookie("csrf_cookie_name",csrf_token)); // Adding a Cookie
var client = new HttpClient(handler);
client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("id", "169486"),
new KeyValuePair<string, string>("csrf_test_name", csrf_token)
};
var content = new FormUrlEncodedContent(pairs);
var response = await client.PostAsync(str, content);
using (FileStream fS = File.Create("result.json"))
{
await response.Content.CopyToAsync(fS);
}
Console.WriteLine(response);
}
I'm trying to POST a Document (any file type) to a GLPI server through API REST.
Here is what I'm doing:
private void button11_Click(object sender, EventArgs e)
{
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
var rcontent = string.Empty;
// HEADERS (URL + Access Tokens)
//string _ContentType = "multipart/form-data";
string _Uri = Properties.Settings.Default.GLPI_URL + "/Document/";
client.BaseAddress = new Uri(_Uri);
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType));
client.DefaultRequestHeaders.Add("Session-Token", Properties.Settings.Default.GLPI_SESSION_TOKEN);
client.DefaultRequestHeaders.Add("App-Token", Properties.Settings.Default.GLPI_APP_TOKEN);
// JSON Content (input string array with file uploaded informations)
JSON_C.DocumentAdder JSONContent = new JSON_C.DocumentAdder();
JSONContent.name = "sth";
JSONContent._filename = filebytes;
HttpContent _JSONContent = new StringContent("uploadManifest={\"input\": " + JsonConvert.SerializeObject(JSONContent).ToString() + "}", Encoding.UTF8, "application/json");
content.Add(_JSONContent);
// File Content in bytes
var fileContent = new ByteArrayContent(filebytes);
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("_filename") { FileName = filepath };
//fileContent.ReadAsByteArrayAsync();
content.Add(fileContent);
// Request
HttpResponseMessage reponse;
var _Method = new HttpMethod("POST");
reponse = client.PostAsync(_Uri, content).Result;
// Request response
rcontent = reponse.Content.ReadAsStringAsync().Result;
textBox2.Text = reponse.ToString() + Environment.NewLine + rcontent.ToString();
}
}
}
But this is what I got in response:
StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Connection: close
Cache-Control: no-store, must-revalidate, no-cache
Date: Mon, 26 Nov 2018 12:50:09 GMT
Server: Apache/2.4.29
Server: (Ubuntu)
Content-Length: 61
Content-Type: application/json; charset=UTF-8
Expires: Mon, 26 Jul 1997 05:00:00 GM
}
With:
["ERROR_UPLOAD_FILE_TOO_BIG_POST_MAX_SIZE","The file seems too big"]
The file I'm trying to upload is 592bytes! Max overall limit in one request is 2Mo. And post_max_size in php.ini is "8M", the same result after I changed it to "0" (for no limit at all). And then set it to 20M to match upload_max_filesize (/etc/php/7.2/apache2/php.ini).
upload_max_filesize_.. is also "20M"
If anyone finding this post and needs help, here is how i managed to succeed :
After separatly creating a "Session-Token", and using "RestSharp".
// Upload
var RSClient = new RestClient(Properties.Settings.Default.GLPI_URL);
var request = new RestRequest("Document", Method.POST);
request.AddHeader("Session-Token", Properties.Settings.Default.GLPI_SESSION_TOKEN);
request.AddHeader("App-Token", Properties.Settings.Default.GLPI_APP_TOKEN);
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "multipart/form-data");
request.AddQueryParameter("uploadManifest", "{\"input\": {\"name\": \"UploadFileTest\", \"_filename\": \"GiletsJaunes.jpg\"}}");
request.AddFile("test", #"C:\path\to\File.jpg");
IRestResponse response = RSClient.Execute(request);
var content = response.Content;
textBox2.Text = textBox2.Text + Environment.NewLine + content;
Details :
I couldn't use RestSharp.Authenticator = new SimpleAuthenticator for some reasons, so i added these Auth params with AddHeader.
I couldn't use a Serialised Json string in a new StringContent, because of AddQueryParameter, so i wrote it manually.
Alleluyah.
I'm new in using twitter API, I've successfully called:
https://api.twitter.com/1.1/statuses/user_timeline.json
api.twitter.com/1.1/followers/list.json
but when I call:
https://api.twitter.com/1.1/geo/search.json?query=Pakistan
I get Forbidden access.
Following is my request:
Method: GET, RequestUri: 'https://api.twitter.com/1.1/geo/search.json?query=Pakistan', Version: 1.1, Content: , Headers:
{
Authorization: Bearer xxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzz%aaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbb
}
And the response that I get is:
StatusCode: 403, ReasonPhrase: 'Forbidden', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
strict-transport-security: max-age=631138519
x-connection-hash: 3a7f405036803861a700cef30f7b1e7f
x-response-time: 107
Date: Fri, 05 May 2017 03:18:15 GMT
Set-Cookie: guest_id=v1%3A149395429589966721; Domain=.twitter.com; Path=/; Expires=Sun, 05-May-2019 03:18:15 UTC
Server: tsa_o
Content-Length: 91
Content-Type: application/json; charset=utf-8
}
If you're interested in looking at my C# code that I'm using, here you go:
public async Task<IEnumerable<string>> GetTweetsByLatLong(double latitude, double longitude, int count, string accessToken = null)
{
if (accessToken == null)
{
accessToken = await GetAccessToken();
}
var requestUserTimeline = new HttpRequestMessage(HttpMethod.Get, string.Format("https://api.twitter.com/1.1/geo/search.json?query=Pakistan"));
requestUserTimeline.Headers.Add("Authorization", "Bearer " + accessToken);
var httpClient = new HttpClient();
HttpResponseMessage responseUserTimeLine = await httpClient.SendAsync(requestUserTimeline);
if (responseUserTimeLine.IsSuccessStatusCode)
{
var serializer = new JavaScriptSerializer();
dynamic json = ((serializer.Deserialize<object>(await responseUserTimeLine.Content.ReadAsStringAsync())) as Dictionary<string, object>).Values.ElementAt(0);
//new System.Collections.Generic.Mscorlib_DictionaryValueCollectionDebugView<string, object>((json as Dictionary<string, object>).Values).Items[0]
var enumerableTwitts = (json as IEnumerable<dynamic>);
if (enumerableTwitts == null)
{
return null;
}
return enumerableTwitts.Select(t => (string)(t["name"].ToString()));
}
else
{
return new string[] { responseUserTimeLine.ToString() };
}
}
public async Task<string> GetAccessToken()
{
var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.twitter.com/oauth2/token ");
var customerInfo = Convert.ToBase64String(new UTF8Encoding().GetBytes(OAuthConsumerKey + ":" + OAuthConsumerSecret));
request.Headers.Add("Authorization", "Basic " + customerInfo);
request.Content = new StringContent("grant_type=client_credentials", Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.SendAsync(request);
string json = await response.Content.ReadAsStringAsync();
var serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>(json);
return item["access_token"];
}
I believe it is because you are using Application-only authentication by providing a Bearer token.
See "Requires Authentication" in both
https://dev.twitter.com/rest/reference/get/geo/search
and
https://dev.twitter.com/rest/reference/get/statuses/user_timeline
And read https://dev.twitter.com/oauth