I am not familiar with REST webservices, but I am trying to get a response from one of them in a C# application.
I am trying to connect to the webservice and authenticate my application to get a token. For this, I have an URL, a login and a password.
When I call the authentication method with cURL tool, I get a « success :true» answer, followed with the token string.
But when I try to do the same with my C# code, I always get a « success :false» answer and no token.
Can somebody help me to understand what is missing in my C# code to get the correct answer ? Thank you.
The cURL request (given by the webservice owner) is:
curl -X POST -d "{\"user\":\"mylogin\",\"pwd\":\"mypassword\"}" \
-H "Content-Type: application/json" http://webserviceURL/authenticate
My code is the following : (restlogin, restpassword and resturl are three strings and get the correct values for the connection. The resulting string is obtained in the variable nammed token).
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resturl + "authenticate");
request.Method = "POST";
request.Credentials = new NetworkCredential(restlogin, restpassword);
request.ContentType = "application/json";
request.Timeout = 30000;
request.ReadWriteTimeout = 30000;
request.Accept = "application/json";
request.ProtocolVersion = HttpVersion.Version11;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream respStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream, Encoding.UTF8);
token = reader.ReadToEnd();
reader.Close();
reader.Dispose();
response.Close();
}
}
As per my comment to the question, you are not sending your credentials in the request body. With request.Credentials you're setting the Authentication Header in your HttpRequest.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resturl + "authenticate");
request.Method = "POST";
request.ContentType = "application/json";
request.Timeout = 30000;
request.ReadWriteTimeout = 30000;
request.Accept = "application/json";
request.ProtocolVersion = HttpVersion.Version11;
// Set your Response body
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"user\":\"" + restlogin + "\"," +
"\"pwd\":\"" + restpassword + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream respStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream, Encoding.UTF8);
token = reader.ReadToEnd();
reader.Close();
reader.Dispose();
response.Close();
}
}
Related
this is my C# code right now.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.upcloud.com/1.2/account");
string authInfo = "username:password";
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers.Add("Authorization", "Basic " + authInfo);
request.ContentType = "application/json";
request.Method = WebRequestMethods.Http.Get;
request.AllowAutoRedirect = true;
request.Proxy = null;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();
Console.Write(s);
The code looks fine to me but I get this exception System.Net.WebException: The underlying connection was closed when trying to get a response (HttpWebResponse response = (HttpWebResponse)request.GetResponse();).
What I'm trying to do is basically "translate" the python example reported here https://www.upcloud.com/support/getting-started-upcloud-api/ to C# but regardless of the many attempts I made I still have not found a solution. Thanks in advance.
I am using .net to connect to PayPal to get access token. I was following the documentary provided on PayPal. https://developer.paypal.com/docs/api/overview/#make-your-first-call
This is what I have so far. Mostly go it from here. Although it connects, it does not return anything back. I tried it on the Postman and I am getting a json object with access token, but nothing is returned here.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.sandbox.paypal.com/v1/oauth2/token");
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(clientId + ":" + clientSecret));
request.Accept = "application/json";
request.Headers.Add("Accept-Language", "en_US");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
byte[] postBytes = Encoding.ASCII.GetBytes("grant_type=client_credentials");
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Flush();
postStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
This is what I am getting from on breakpoints.
response.CharacterSet = ""
response.ContentLength = 899
response.StatusCode = OK
Found the answer. The following code provides the json object.
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString); // This will display the answer as JSON, now just parse it.
Follow PayPal's .NET SDK Quick Start guide. You can authenticate and get your access token as follows:
using PayPal.Api;
// Authenticate with PayPal
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
I'm stucked here at getting a WebResponse from HTTPWebRequest.
The WebRequest.GetResponse() Method throws a WebException
("500 Internal Server Error"). When i read the returned HTML it says:
HTTP 403: Forbidden ('_xsrf' argument missing from POST)
Anyone knows this Error or knows what Im doing wrong?
(Im trying to log in to a Website using POST)
EDIT:
My sourcecode:
private String GetLoginCookies(String pHTTPurl, String pUserIDwithFormID, String pPasswordWithFormID)
{
String loginPageUrl = pHTTPurl;
CookieContainer cookieContainer = new CookieContainer();
var Request = (HttpWebRequest)WebRequest.Create(loginPageUrl);
Request.CookieContainer = cookieContainer;
Request.Method = "GET";
WebResponse Response = Request.GetResponse();
HttpWebResponse HttpResponse = Response as HttpWebResponse;
CookieCollection cookies = null;
if (HttpResponse != null)
{
//Cookies die benötigt werden um den Loginvorgang abzuschließen
cookies = HttpResponse.Cookies;
}
string formParams = string.Format(pUserIDwithFormID + "&" + pPasswordWithFormID);
Request = (HttpWebRequest)WebRequest.Create(loginPageUrl);
Request.CookieContainer = cookieContainer;
Request.UserAgent = "I am not a Bot! Ok maybe..";
WebResponse resp = null;
Request.ContentType = "application/x-www-form-urlencoded";
Request.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
Request.ContentLength = bytes.Length;
using (Stream os = Request.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
try
{
resp = Request.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
String TestResponse = sr.ReadToEnd();
}
}
catch (WebException WE)
{
DebugConsole.AppendText("HTTP Error:" + WE.Message + Environment.NewLine);
String HTML = new StreamReader(WE.Response.GetResponseStream()).ReadToEnd();
DebugConsole.AppendText(HTML);
return null;
}
String cookieHeader = resp.Headers["Set-cookie"];
if (String.IsNullOrEmpty(cookieHeader))
return null;
else
return cookieHeader;
}
This is actually because the web method requires anti csrf (cross site request forgery, more info here: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)) validation parameter. What you can do, is to append the csrf value to the request header:
postHeaders.Add("X-CSRFToken", CSRF);
Maybe you can paste your source code here if you need any help with that, so we can look after it
OK! Solution found!
After getting the response of the Log-In site, search in the "Set-cookie" Header for _xsrf. This is the Token you have to put in the header of the next POST request.
I have rest api url like this
https://example.com/ProductAPI/api/V1/getproduct.
This api has api_key,username and password.How can I access this api and getproduct details using c#.I tried like this
WebRequest request = WebRequest.Create(#"https://example.com/ProductAPI/api/V1/getproduct");
request.Method = "GET";
request.Headers.Add("api_key","5g13441f-6915-4a34-8a53-bcb4er88b554");
request.Headers["Authorization"] = "Basic" + Convert.ToBase64String(Encoding.Default.GetBytes("admin:123"));
request.ContentLength = 0;
request.ContentType = #"application/json; charset=utf-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string jsonResponse = string.Empty;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
jsonResponse = sr.ReadToEnd();
Console.WriteLine(jsonResponse);
Console.ReadLine();
}
But it show 401 unauthorized error.Pls help to solve this
curl https://api.stripe.com/v1/charges
\ -u sk_test_BQokikJOvB432343iI2HlWgH4olfQ2:
\ -d amount=400
\ -d currency=usd
\ -d card=tok_15CVG02eZvKYlo2CDVUHUs56
I'm new to curl and need to convert the above curl request into an ASP.NET web request. I believe the -d are post parameters, but I am unsure how to pass in the -u and what -u stands for. Below is the code I have so far. FYI this is for the Stripe Payment Gateway, I can't use the ASP.NET Library because I can add any dlls to the solution I am running so I am using their CURL API.
string formencodeddata = "amount=400¤cy=usd&card=tok_15CVG02eZvKYlo2CDVUHUs56";
byte[] formbytes = System.Text.ASCIIEncoding.Default.GetBytes(formencodeddata);
//Create a new HTTP request object, set the method to POST and write the POST data to it
var webrequest = (HttpWebRequest)WebRequest.CreateHttp("https://api.stripe.com/v1/charges");
webrequest.Method = "POST";
webrequest.ContentType = "application/x-www-form-urlencoded";
using (Stream postStream = webrequest.GetRequestStream()) {
postStream.Write(formbytes, 0, formbytes.Length);
}
//Make the request, get a response and pull the data out of the response stream
var webresponse = (HttpWebResponse)webrequest.GetResponse();
Stream responseStream = webresponse.GetResponseStream();
var reader = new StreamReader(responseStream);
string result = reader.ReadToEnd();
This was my final solution:
var postUrl = new StringBuilder();
postUrl.Append("card=");
postUrl.Append(token);
postUrl.Append("currency=usd");
postUrl.Append("&x_amount=");
postUrl.Append(transactionAmount.ToString());
byte[] formbytes = System.Text.ASCIIEncoding.Default.GetBytes(postUrl.ToString());
//Create a new HTTP request object, set the method to POST and write the POST data to it
var webrequest = (HttpWebRequest)WebRequest.Create(Url);
webrequest.Method = "POST";
webrequest.UserAgent = "Stripe Payment Processor";
webrequest.ContentType = "application/x-www-form-urlencoded";
webrequest.Headers.Add("Stripe-Version", "2014-12-22");
webrequest.Headers.Add("Authorization", String.Concat("Basic ", (Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:", this.PrivateKey))))));
using (Stream postStream = webrequest.GetRequestStream())
{
postStream.Write(formbytes, 0, formbytes.Length);
}
//Make the request, get a response and pull the data out of the response stream
StreamReader reader = null;
string stripeResponse;
try
{
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
Stream responseStream = webresponse.GetResponseStream();
reader = new StreamReader(responseStream);
stripeResponse = reader.ReadToEnd();
}
catch (WebException exception)
{
using (WebResponse response = exception.Response)
{
using (Stream data = response.GetResponseStream())
using (reader = new StreamReader(data))
{
stripeResponse = reader.ReadToEnd();
}
}
}