RestSharp no response when Transfer-Encoding: chunked - c#

I am trying to use a very simple RestSharp client like this
RestClient client = new RestClient(#"http://hostname:28000");
RestRequest request = new RestRequest(Method.GET);
request.AddParameter("action", "getstatus");
var res = client.Execute(request);
However, this always fails with
System.IO.InvalidDataException: Block length does not match with its complement.
So the response does not contain any data.
What I noticed when I execute the request in a webrowser with a network tracer, it shows the Transfer-encoding as "chunked". This somehow seems to hinder RestSharp.
Running the same request with standard HttpWebRequest works fine.
Any ideas how to solve this with RestSharp?
//edit: The response should be a valid XML.

Related

GET request works on Postman but fail with RestSharp

I know that similar questions have been already posted in the past but I read a lot on the subject and still couldn't find an answer to my problem.
I have a GET request that works fine on Postman:
I translated it with the Code tool in C# - RestSharp and tested it with my plugin but somehow I always get the same error:
My C# - RestSharp code (It's the one I get with the Postman translator):
var client = new RestClient("https://..........."); //my url
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Cookie", ".........."); //my cookie
IRestResponse response = client.Execute(request);
I tried adding all the headers visible in the Headers section:
request.AddHeader("User-Agent", "PostmanRuntime/7.29.0");
request.AddHeader("Accept", "*/*");
request.AddHeader("Accept-Encoding", "gzip, deflate, br");
request.AddHeader("Connection", "keep-alive");
without result. The Authorization type is No Auth. Any idea?
Maybe it has something to do with the fact that the response body in Postman is a plain text? The other requests I send that have a JSON response works perfectly fine.
Thank you for your help!
Use request.AddCookie(cookiename, cookievalue);

HTTP Request works in postman but doesn't work in code

I'm trying to access a website that requires login via a form.
I used the Postman HTTP client.
I tried to do the normally http post request but didn't seem to work, I get a successful status code (200 OK) but it doesn't log in, eventually did work with a GET request with BODY parameters (I hadn't seen GET request with body parameters).
Well, I tried to simulate this request in C# code with no luck, I even tried the generated code that Postman offers with no luck again.
Down below is the Postman request and the C# code snippet based on auto-generated Postman code. Does anyone know if is there to make this request with any library or if there is something that I miss?
Thank you in advance.
var client = new RestClient("https://thessalia-3.teilar.gr/login.asp");
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Referer", "https://thessalia-3.teilar.gr/login.asp");
var parameters = new Dictionary<string, string>();
parameters["userName"] = JsonConvert.SerializeObject("myusername");
parameters["pwd"] = JsonConvert.SerializeObject("mypass");
parameters["loginTrue"] = JsonConvert.SerializeObject("extravalue");
var content = new FormUrlEncodedContent(parameters);
request.AddParameter("application/x-www-form-urlencoded", content);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Console.WriteLine(response.StatusCode);
Postman Request Photo
Edit:
Postman Request Body Parameters
I've also tried to run this but also not logged in.
Auto-generated code form Postman
If the request was successful (200) and you got the HTML page for "Invalid Credentials", then your code that's making the request should be fine and the issue is with the credentials. Like I said in my first comment, don't serialize the parameters to JSON, URL-encode them instead:
parameters["userName"] = HttpUtility.UrlEncode("myusername");
parameters["pwd"] = HttpUtility.UrlEncode("mypass");
parameters["loginTrue"] = HttpUtility.UrlEncode("extravalue");
This is the standard way and it works with writing the parameters directly to the request stream, or with a utility class like StringContent. However, since you're using the utility class FormUrlEncodedContent, it URL-encode them for you, so you don't have to. In that case, simply assign them directly as string:
parameters["userName"] = "myusername";
parameters["pwd"] = "mypass";
parameters["loginTrue"] = "extravalue";

Yelp Fusion API v3 returns 401 Unauthorized with TOKEN_MISSING error when called from c#

I've created my app in Yelp, got my api key, and things work fine from Postman when executing a business search.
However, when testing from c#, I receive a 401 unauthorized error with a TOKEN_MISSING error that says ""{\"error\": {\"code\": \"TOKEN_MISSING\", \"description\": \"An access token must be supplied in order to use this endpoint.\"}}"".
I'm supplying my api key correctly though, and the Yelp documentation says that's all I need, so I'm not sure what the problem is. Here are 2 separate c# code samples that do NOT work (I've replaced my actual api key with for security concerns):
Example using WebRequest:
var webRequest = WebRequest.Create("http://api.yelp.com/v3/businesses/search?term=Clayton+Bicycle+Center&location=5411+Clayton+Rd%2c+Clayton%2c+CA+94517%2c+US");
webRequest.Method = "GET";
webRequest.Headers.Add("Cache-Control", "no-cache");
webRequest.Headers.Add("Authorization", "Bearer <my_api_key>");
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
var stream = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
var content = stream.ReadToEnd();
Console.Write(content);
Example using RestSharp:
var client = new RestClient("http://api.yelp.com/v3/businesses/search?term=Clayton+Bicycle+Center&location=5411+Clayton+Rd%2c+Clayton%2c+CA+94517%2c+US");
var request = new RestRequest(Method.GET);
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Authorization", "Bearer <my_api_key>");
var response = client.Execute(request);
Console.Write(response.Content);
I've examined the requests in Fiddler, and both are sending the same headers as the working Postman search, but both return 401 unauthorized error while Postman returns the search results. Any ideas?
Edit:
Well this is embarrassing, apparently my issue was I was attempting to access the Yelp API via http instead of https. Once I changed to https, everything worked as expected.
Changed endpoint to use https instead of http, works now.

C#: RestClient: RestRequest fails for lower case header

I have the code below in c#, which uses RestClient. The issue is that the headers should not be case-sensitive but looks like they are.
var client = new RestClient(sMA_URL);
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
//Without the line below the RestRequest adds some default header which is not acceptable by our server.
request.AddHeader("**Accept**", "*/*");
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", "Bearer "+sBearerToken);
// Make sure you deserialize this response, for further use. The best way to do this is to create a class and then fill that with the values obtained by the response but if a response is not used many times,
// you can do it the way it has been done in Bearer Token Generation
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Console.ReadKey();
When I give accept (in lower case) it complains about the content-type but Accept (upper case) works fine.No, error regarding the content-type. I can't figure out if the issue is with the service it's trying to call or with RestClient itself.
This is the status code I get (No exception)
'NotAcceptable Content-Type'
Well the answer is included in the response, its self explanatory.
"NotAcceptable Content-Type"
The message above means that the api, service or endpoint your are trying sending your request to, rejects your request based on the content-type header which is 'application/json'.
Since you are sending a GET request, i don't see why do you need to specify content-type at all.
Try removing the content-type header and probably your request will work.
Adding the content-type header would be used for POST or PUT requests, where you are sending a body/payload in the request (example: json,form data,xml,multipart,etc...), and even for this type of requests it is still not mandatory unless the server you are sending your requests to requires you to specify the content-type.

DotNetOpenOAuth Content-type

I am tearing my the remainings of my hair off trying to solve an issue with DotNetOpenOAuth. Below are the details of the problem.
Consumer = new DesktopConsumer(xeroProviderDescription, _tokenManager);
var endPoint = new MessageReceivingEndpoint(apiEndPoint, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
var request = Consumer.PrepareAuthorizedRequest(endPoint, accessToken);
var content = Encoding.UTF8.GetBytes(payload);
request.ContentType = "application/json";
request.ContentLength = content.Length;
This works perfectly fine, the server accepts the request and replies. Now, I want to switch to using xml to talk to the remote service (this is their prefered format over json) So I changed all the code into sending XML data instead of json and changed the content-type to application/x-www-form-urlencoded as per the web service provider documentation. The problem now is that the service is returning 401 unauthorized request - Reason: invalid signature whenever application/x-www-form-urlencoded is used
Questions:
Is the Content-Type taken into account when generating the oauth signature (I looked into the DotNetOpenOAuth source code with no luck)?
Anyone has ever encountered this issue and resolved it?

Categories

Resources