My goal is to download a file with a RestSharp GET by passing along a Json body and a security token in the header. For now, I'm just trying to get a response.
I got this code from Postman, where the GET is working (I am prompted where to save the file).
var client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", token);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", json, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
string responseMsg = "";
if (response.Content == "")
responseMsg = response.ErrorMessage
else
responseMsg = response.Content
return responseMsg;
The only response that I'm getting is the ErrorException "HTTP verb GET does not support body".
So I believe there is an issue with my logic, not my Json or token. Does anything in my code look incorrect?
Application framework: .Net 4.8
RestSharp version: 106.15.0
Thanks.
Edit:
As mentioned below, a GET request with a body parameter is invalid. After removing the the json body, the request is now working.
var client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", token);
IRestResponse response = client.Execute(request);
In the case of my application, the unique identifier was appended to the endpoint, so only the security token was needed as a header.
GET requests cannot have bodies, or rather, they can, but that behaviour is not defined and so some implementations will reject the request entirely. It appears that RestSharp also intentionally does not support GET requests with bodies for the same reason. According to that thread, .NET itself may support them, so you might wish to try that if it's absolutely necessary.
Whether or not you should do that might come under the umbrella of personal opinion, however with that in mind I would caution against doing things outside of the specification, because any updates to libraries or frameworks have no guarantee of consistency of behaviour when they're being used out of spec. If this is an API you have control over, you should consider bringing it in-spec. If it's not, you should consider contacting the developer to have them look into it.
Related
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);
I have my telegram application with app's api_id and app's api_hash.
I used TLSharp library for implementing my own things. But now I need to use this https://core.telegram.org/method/auth.checkPhone telegram api method, but it's not implemented in TLSharp library!
I don't mind doing it all manually, but I don't know how!
I know how you send post requests in C#, example:
var response = await client.PostAsync("http://www.example.com/index", content);
but in this specific case I don't. Because I don't know:
1) what link should I use for sending post requests? I couldn't find it on the telegram's website.
2) what content should I pass there? Should it be just "(auth.checkPhone "+380666454343")" or maybe the whole "(auth.checkPhone "+380666454343")=(auth.checkedPhonephone_registered:(boolFalse)phone_invited:(boolFalse))" ?
So, How do I sent this post request to the telegram api? (NOT telegram bot api!)
Try to use System.Net.Http like in this example (auth request to the server):
var user = new { login = "your login", password = "your pass" };
string json = JsonConvert.SerializeObject(user);
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage();
request.RequestUri = new Uri("server route link"); // can be like https://a100.technovik.ru:1000/api/auth/authenticate
request.Method = HttpMethod.Post;
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
responseText.Text = await response.Content.ReadAsStringAsync();
I think based on a brief look, that it would be more along the lines of your second example, e.g.:
var phonenumber = "0123456789";
var content =
$#"(auth.checkPhone ""{phonenumber}"")"+
"=(auth.checkedPhone phone_registered: (boolFalse) phone_invited:(boolFalse))";
var result = DoHttpPost("http://some.example.com/api/etc", content);
(note: I've not listed the actual mechanics of an HTTP Request here, as that is covered in plenty of detail elsewhere - not least in the other current answer supplied to you; DoHttpPost() is not a real method and exists here only as a placeholder for this process)
And since the payload of this appears to indicate the exact function and parameters required, that you'd just send it to the base api endpoint you use for everything, but I can't say for sure...
I do note they do appear to have links to source code for various apps on the site though, so perhaps you'd be better off looking there?
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";
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.
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.