RestSharp - cannot connect to remote server - c#

I have a problem with RestSharp request - it is working when running in Test project but returning "Unable to connect to remote server" when running inside MVC.
var client = new RestClient("https://apiurl");
var request = new RestRequest("Authenticate", Method.POST);
request .AddHeader("Accept", "text/json");
request .AddHeader("Content-Type", "text/json");
var model = new AuthenticationRequest
{
Username = "username",
Password = "passowrd"
};
string body = JsonConvert.SerializeObject(model);
request.AddParameter("text/json", body, ParameterType.RequestBody);
var response = client.Execute(request);
Same code in test is working just fine. But inside MVC on localhost I get "Unable to connect to remote server". Anyone had similar issue?
Thanks in advance for the help!

Related

C# Oracle Rest API, Authentication Issue

I am trying to use Ocacle's Financial REST API and I'm having trouble making it work in C# in VS2019.
I can confirm the restful call works using Postman, so I know my credentials are fine but I must be missing something trying this with in code.
So URL is like so:
http://MYCLOUDDOMAIN/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail
So I stick that in postman, put in my credentials (basic auth) and it works find. In VS I've tried both the RestSharp way and basic HTTPRequest way as follows:
HttpWebRequest r = (HttpWebRequest)WebRequest.Create("/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger US,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail");
r.Method = "GET";
string auth = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("Username" + ":" + "Password"));
r.Headers.Add("Authorization", "Basic" + " " + auth);
r.ContentType = "application/vnd.oracle.adf.resourcecollection+json";
using (HttpWebResponse resp = (HttpWebResponse)r.GetResponse())
{
int b = 0;
}
RestSharp:
var client = new RestClient("http://MYCLOUDDOMAIN/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger US,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail");
client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("UserName", "Password");
//Tried authorization this way as well.
//JObject AuthRequest = new JObject();
//AuthRequest.Add("Username", "UserName");
//AuthRequest.Add("Password", "Password");
var request = new RestRequest();
request.Method = Method.GET;
request.RequestFormat = DataFormat.Json;
//request.AddParameter("text/json", AuthRequest.ToString(), ParameterType.RequestBody);
request.AddHeader("Content-Type", "application/vnd.oracle.adf.resourcecollection+json");
request.AddHeader("REST-Framework-Version", "1");
var response = client.Get(request);
No matter what I try I am always 401 not authorized. I suspect its some kind of header thing? I can't see the raw request header in postman
I am new to REST. I am used to using WSDLs soap services.
Try this.
var handler = new HttpClientHandler
{
Credentials = new NetworkCredential("username", "password")
};
using (var client = new HttpClient(handler))
{
var result = await client.GetAsync("url");
}
Good luck!
I figured out what the problem was.
In postman, it was fine with the URL I posted being HTTP but in C# code it was not. I switched the URL to HTTPS and it started working just fine.

RestSharp Unable to connect to remote server

I am trying to use RestSharp in a console application, to connect to an api and get a cookie, but in the response, i keep getting "Unable to connect to remote server".
var client = new RestClient("http://finans-dk.pronestor.com/Api.mvc/v1/Authenticate");
client.Authenticator = new SimpleAuthenticator("login", "????", "password", "????");
var request = new RestRequest("resource", Method.GET);
IRestResponse response = client.Execute(request);
I basically expect RestSharp to call the following:
finans-dk.pronestor.com/Api.mvc/v1/Authenticate?login=???&password=???
This works for me in postman, but not in restsharp.
I have tested with http://ip.jsontest.com, to test if i can connect to any outside apis, this works and get my ip back.
Any ideas???
Change your code to this:
var client = new RestClient("https://finans-dk.pronestor.com/Api.mvc/v1/");
client.Authenticator = new SimpleAuthenticator("login", "????", "password", "????");
var request = new RestRequest("Authenticate", Method.GET);
IRestResponse response = client.Execute(request);
You didn't look at the documentation you linked to properly. In its example the URL is:
http://example.com/resource?username=foo&password=bar
Pay attention to where resource appears. Your URL shows Authenticate in that place instead.

401 Unauthorized after release site

I have my web api which uses such code to get data from other api and do some operations with it :
var credential = new NetworkCredential("login", "password");
var myCache = new CredentialCache();
myCache.Add(uri, "Negotiate", credential);
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
handler.Credentials = myCache;
var httpClient = new HttpClient(handler);
var response = await httpClient.GetStringAsync(GetEmployeesUrl);
employees = JsonConvert.DeserializeObject<IEnumerable<EmployeeDto>>(response);
When I was debugging this code with IIS Express on my local host it's pretty good works and give me OK response from server. When I tried to deploy my api to real IIS this var response = await httpClient.GetStringAsync(GetEmployeesUrl);always returns 401 Unauthorized error.
Have someone some ideas what it can be? I have used webclient and webrequest they worked on my local machine but answer after deploy on server was the same.

Accessing HTTPS URL With Credentials

I have a HTTPS URL which i am trying to connect to but not able to and keep getting 401 unauthorized.
I tried to access the same URL over Web Browser (both at home and in company) and was able to connect to it. After i execute the HTTPS URL (which has some parameters in it like date etc) in the browser, it prompts for username and pwd and when i enter it, it gives the xml back in response.
I tried following segment of code on my home PC and it worked fine but when i tried same in office network, it gave me 407 error. I thereafter embedded the proxy code in it and now i don't get 407 rather i keep getting 401. Please help
Working Code on Home:
public static void WorkingCode()
{
string URL = "https://webservice.XYZ.com/display/?start_date=2015-05-06&end_date=2015-05-07";
Uri uri = new Uri(URL);
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("username123", "Password123");
string results;
results = wc.DownloadString(uri);
Console.Write(results);
Console.Read();
}
Code within Organization with PROXY:
public static void WorkingCode()
{
string URL = "https://webservice.XYZ.com/display/?start_date=2015-05-06&end_date=2015-05-07";
Uri uri = new Uri(URL);
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("username123", "Password123");
string results;
/* PROXY CODE*/
WebProxy myProxy = new WebProxy("frproxyseczom.PPP.com", 8080);
myProxy.UseDefaultCredentials = true;
wc.Proxy = myProxy;
/*---------------*/
results = wc.DownloadString(uri);
Console.Write(results);
Console.Read();
}
Because of security reasons, i have modified some details such as URL's, username and pwd.
You're probably getting a 401 in the proxy code because you're missing "http://" in the web proxy address.

c# webclient upload and download data from ssl

I have a wamp server on windows. SSL configured correctly. In browser it is working threw https: . I have a script test.php and I want to download and upload some POST data to it. I have my c# code:
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
NameValueCollection values = new NameValueCollection();
values.Add("paramtest", "testval");
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] result;
result = client.UploadValues("https://127.0.0.1./test.php", "POST", values);
string htmlCode = Encoding.UTF8.GetString(result);
textBox1.Text = htmlCode;
When runnign this code with http I got all the data. When put https, I got an error from the server:
400 Bad Request Bad Request
Your browser sent a request that this server could not
understand.
Have you got any idea how can I fix it?
Not sure whether this is the cause, but your url has a trailing '.' after the IP address:
try
result = client.UploadValues("https://127.0.0.1/test.php", "POST", values);
instead of
result = client.UploadValues("https://127.0.0.1./test.php", "POST", values);

Categories