RestClient works but HttpWebRequest doesn't - c#

This code works:
var source = "https://jade.io/xml/au-qld-dc.xml";
var client = new RestClient(source);
var request = new RestRequest(Method.GET);
IRestResponse resp = client.Execute(request);
Console.WriteLine(resp.Content);
The xml is retrieved and displayed in the Console.
But this code doesn't work:
HttpWebRequest httpsRequest = (HttpWebRequest) WebRequest.Create(source);
httpsRequest.Method = "GET";
var response = httpsRequest.GetResponse();
It throws a 403 (Forbidden) error...
I'd like to know why it doesn't work, because I have some legacy code using WebRequest, and before replacing all that code with RestClient, if there is an easy fix...

Add UserAgent header and it will work.
var source = "https://jade.io/xml/au-qld-dc.xml";
HttpWebRequest httpsRequest = (HttpWebRequest)WebRequest.Create(source);
httpsRequest.Method = "GET";
httpsRequest.UserAgent = "Test";
var response = httpsRequest.GetResponse();

Related

Is there any possibility to send post with body using OAuth 1.0?

i am trying to send a POST request with body to WordPress API. I am still getting 401 error.
I decided to use: https://gist.github.com/DeskSupport/2951522 to authorize via OAuth 1.0 and it works perfectly with GET method. Then i wanted to implement another method which sends simple body.
That's my code:
var oauth = new OAuth.Manager();
oauth["consumer_key"] = _consumerKey;
oauth["consumer_secret"] = _consumerSecret;
oauth["token"] = _accessToken;
oauth["token_secret"] = _tokenSecret;
var appUrl = _baseUrl + url;
var authzHeader = oauth.GenerateAuthzHeader(appUrl, "POST");
string body = GenerateBody(parameters);
byte[] encodedData = Encoding.ASCII.GetBytes(body);
var request = (HttpWebRequest)WebRequest.Create(appUrl);
request.Method = "POST";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.Headers.Add("Authorization", authzHeader);
request.ContentLength = encodedData.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream newStream = request.GetRequestStream();
newStream.Write(encodedData, 0, encodedData.Length);
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
}
}
The result of method GenerateBody is user_login=login&user_pass=BXE&04K44DoR1*a
I also tried to change the '&' character to '%26' but it didn't work.
This request works via Postman and i don;t know what's wrong.
OK, I found a solution.
https://blog.dantup.com/2016/07/simplest-csharp-code-to-post-a-tweet-using-oauth/
This guy wrote the way to make this request. What is also important you have to change a oauth_nonce for unique token.

RestSharp proxy http/https/socks information

I wanted to know what kind of proxies are compatible with RestSharp and how to use them?
You can use System.Net WebProxy as below.
var request = new RestRequest(funcName, funcType);
request.RequestFormat = DataFormat.Json;
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json";};
request.AddBody(param);
RestClient restClient = new RestClient(url);
restClient.Proxy = new WebProxy(myProxyUrl, myProxyHost);
restClient.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
var value = restClient.Execute(request);

Get GitHub Rest API User info C# code

https://api.github.com/users/[UserName] can be accessed via browser. I get a Json result. But I want to retrieve the same information programmatically.
I'm using the below code, which is not working as expected. Please advice.
var credentials =
string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:",
githubToken);
credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("Basic", credentials);
var contents =
client.GetStreamAsync("https://api.github.com/users/[userName]").Result;
As a result of the above code, I'm getting "Aggregate Exception".
How to achieve the requirement using c# code??? Please help
Note: Not expecting a solution with Octokit. Need proper c# code.
I found the solution. Here is the code.
HttpWebRequest webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Method = "GET";
webRequest.UserAgent = "Anything";
webRequest.ServicePoint.Expect100Continue = false;
try
{
using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
string reader = responseReader.ReadToEnd();
var jsonobj = JsonConvert.DeserializeObject(reader)
}
}
catch
{
return;
}
}

“500 error” in file-upload for REST API using C# client

I have to upload a file to third party server using REST API. I have bare minimum document is available for that REST method.
When I use Postman to call the service, it works. Part of the generated code in Postman for C# is like this :
var client = new RestClient("<URL>");
var request = new RestRequest(Method.POST);
request.AddHeader("postman-token", "6cb9f00b-e1ac-f8d8-b5d6-eeb67b06ae6a");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Basic cm9vdDpIaXRhY2hpQDEy");
request.AddHeader("content-type", "multipart/form-data; boundary=-- -011000010111000001101001");
request.AddParameter("multipart/form-data; boundary=-- -011000010111000001101001", "-----011000010111000001101001\r\nContent- Disposition: form-data; name=\"file\"; filename=\"[object Object]\"\r\nContent-Type: false\r\n\r\n\r\n-----011000010111000001101001--", ParameterType.RequestBody);
RestResponse response = client.Execute(request);
The following code written in Python also works –
vroAuth = requests.auth.HTTPBasicAuth("<username>","<Password> ")
url = <url>
files = {"file":open("<absolute file path on client machine>",'rb')}
response_output = requests.post(url, auth=vroAuth,files=files, verify=False)
Based on these two code snippets ,I tried to write client code in C# like this:
HttpWebRequest request = HttpWebRequest.Create(restBaseUrl) as HttpWebRequest;
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
ServicePoint sp = request.ServicePoint;
var fl = Path.GetFileName(fileName);
request.Method = "POST";
request.Timeout = 60 * 60 * 1000;
request.Accept = "application/json";
request.AllowAutoRedirect = false;
String headerInfo = "file; filename=" + fileName;
request.Headers["Content-Disposition"] = headerInfo;
request.ContentType = "multipart/form-data;";
request.Credentials = new NetworkCredential(userName, password);
using (var strm = request.GetRequestStream())
{
using (var file = File.OpenRead(fileName))
{
file.CopyTo(strm);
}
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
There , I am getting “error 500 – Internal server error”. Unfortunately, there is no information in the header returned from the server. If I try different Content Type for request ( for example - "application/octet-stream";, I am getting error 415 – Media type not supported). All I know is “file” is one of the parameters with Data type as “File”. Any suggestion, how can I proceed to resolve the issue ?

RestSharp - Authorization Header not coming across to WCF REST service

I am trying to call a locally hosted WCF REST service over HTTPS with basic auth.
This works and the Authorization header comes thru just fine and all is happy:
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var request = (HttpWebRequest)WebRequest.Create("https://localhost/MyService/MyService.svc/");
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add(
System.Net.HttpRequestHeader.Authorization,
"Basic " + this.EncodeBasicAuthenticationCredentials("UserA", "123"));
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
if (webStream != null)
{
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
}
}
}
When I try to use RestSharp however, the Authorization header never comes thru on the request:
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var credentials = this.EncodeBasicAuthenticationCredentials("UserA", "123");
var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
var restRq = new RestSharp.RestRequest("/");
restRq.Method = Method.GET;
restRq.RootElement = "/";
restRq.AddHeader("Authorization", "Basic " + credentials);
var restRs = client.Execute(restRq);
What am i doing wrong with the RestSharp method?
I know that the AddHeader method works because this:
restRq.AddHeader("Rum", "And Coke");
will come thru, only "Authorization" seems stripped out/missing.
instead of adding the header 'manually' do the following:
var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
client.Authenticator = new HttpBasicAuthenticator("UserA", "123");
I used milano's answer to get my REST service call to work (using GET)
Dim client2 As RestClient = New RestClient("https://api.clever.com")
Dim request2 As RestRequest = New RestRequest("me", Method.GET)
request2.AddParameter("Authorization", "Bearer " & j.access_token, ParameterType.HttpHeader)
Dim response2 As IRestResponse = client2.Execute(request2)
Response.Write("** " & response2.StatusCode & "|" & response2.Content & " **")
The key was making sure there was a space after the word 'Bearer' but this may apply to any type of custom token authorization header
You have to use ParameterType.HttpHeader parameter:
request.AddParameter("Authorization", "data", ParameterType.HttpHeader);
I was able to get the response from my rest API using this piece of code:
My API was returning server error and I used:
request.AddHeader("Authorization", $"Bearer {accessToken}");
var request = new RestRequest("/antiforgerytokensso", Method.Get);
restClient.Authenticator = new JwtAuthenticator(accessToken);
var response = await restClient.ExecuteAsync(request);
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));

Categories

Resources