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.
Related
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 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();
}
}
I am trying to write a YouTube app for windows phone, and I stumbled upon some problems on the authentication side. For some reason the following code is not working properly,
string url = "https://accounts.google.com/o/oauth2/token?";
string postData = "code=" + str + "&client_id=*********.apps.googleusercontent.com&client_secret=*******&grant_type=authorization_code";
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url);
byte[] data = Encoding.Unicode.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
using (Stream stream =await httpWReq.GetRequestStreamAsync())
stream.Write(data, 0, data.Length);
HttpWebResponse response =(HttpWebResponse)(await httpWReq.GetResponseAsync());
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
I am fairly new to HttpWebRequest so probably I missed something, although I am getting a response:
Bad Request
To be specific it says that grant_type is missing although I am pretty sure that it is not, I did everything according to the documentation. What am I doing wrong ?
This will probably fix it
parameters.Append("code=" + str);
parameters.Append("&client_id=*****.apps.googleusercontent.com");
parameters.Append("&client_secret=*****");
parameters.Append("&redirect_uri=urn:ietf:wg:oauth:2.0:oob:auto");
parameters.Append("&grant_type=authorization_code");
string p_params = parameters.ToString();
byte[] p_data_params = Encoding.UTF8.GetBytes(p_params);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
request.Accept = "application/json";
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = await request.GetRequestStreamAsync();
dataStream.Write(p_data_params, 0, p_data_params.Length);
dataStream.Dispose();
HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
Stream responseStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8);
string result = readStream.ReadToEnd();
Works fine for me.
/*WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
string parameters = "code=4/f2PwqbN1Z5FpEEcT0scRH20B6d-F.ouqZIhzZqUYbEnp6UAPFm0EuJPwSigI&" +
"client_id=162438320977-ml14ajmuutlrr71maal933ma5cjolc8l.apps.googleusercontent.com&" +
"&client_secret=1IJxvSnmxcx-i2l_YGgYOD0i&redirect_uri=http://localhost&grant_type=authorization_code";
byte[] data = Encoding.UTF8.GetBytes(parameters);
var test = client.UploadData("http://accounts.google.com/o/oauth2/token","POST", data);
string result = data.ToString();*/
StringBuilder parameters = new StringBuilder();
parameters.Append("code=4/IoAJMoYxUqk7lkH_WbSr3lk4URf1.0t7Qx7qZE5QeEnp6UAPFm0G0EvMSigI");
parameters.Append("&client_id=162438320977-ml14ajmuutlrr71maal933ma5cjolc8l.apps.googleusercontent.com");
parameters.Append("&client_secret=1IJxvSnmxcx-i2l_YGgYOD0i");
parameters.Append("&redirect_uri=urn:ietf:wg:oauth:2.0:oob");
parameters.Append("&grant_type=authorization_code");
string p_params = parameters.ToString();
byte[] p_data_params = Encoding.UTF8.GetBytes(p_params);
HttpWebRequest request = (HttpWebRequest) WebRequest.Create("https://accounts.google.com/o/oauth2/token");
request.Accept = "application/json";
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = p_data_params.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(p_data_params, 0, p_data_params.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8);
string result = readStream.ReadToEnd();
The only approach that seems to work for me is using HttpWebRequest. I found the answer here: .Net Google OAuth token WebRequest Bad Request Protocol Error If anyone knows of a way to get the Web Client implementation working please let me know! Thanks.
I am giving two calls to one remote REST service one after the other in single method. I am setting value of accessToken in first call and using it for the second request.
When I am running it, it is giving me error as
The remote server returned an error: (500) Internal Server Error.
Following is the code.
HttpWebRequest webRequest = null;
HttpWebResponse webResponse = null;
Encoding encodingObj = null;
StreamReader streamReaderObj = null;
string grantCode = string.Empty;
string resultString = string.Empty;
string accessToken = string.Empty;
private void Instantiate()
{
grantCode = HttpContext.Current.Request.QueryString["code"].ToString();
webRequest = (HttpWebRequest)WebRequest.Create(Constants.ACCESS_TOKEN_REQUEST + "&code=" + grantCode);
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
webResponse = (HttpWebResponse)webRequest.GetResponse();
encodingObj = System.Text.Encoding.GetEncoding("utf-8");
streamReaderObj = new StreamReader(webResponse.GetResponseStream(), encodingObj);
resultString = streamReaderObj.ReadToEnd();
JObject parameterCollection = JObject.Parse(resultString);
accessToken = parameterCollection["access_token"].ToString();
//HttpContext.Current.Response.Write("<br/><br/>Code: <br/>" + grantCode);
//HttpContext.Current.Response.Write("<br/><br/>Access Token: <br/>" + accessToken);
webRequest = (HttpWebRequest)WebRequest.Create(Constants.RETRIEVE_CONTEXT_REQUEST + "vista-688/id/Staff01");
webRequest.Method = "GET";
webRequest.Accept = "application/json";
webRequest.ContentType = "application/json";
webRequest.Headers.Add("Authorization", "Bearer " + accessToken);
webResponse = (HttpWebResponse)webRequest.GetResponse();
encodingObj = System.Text.Encoding.GetEncoding("utf-8");
streamReaderObj = new StreamReader(webResponse.GetResponseStream(), encodingObj);
resultString = streamReaderObj.ReadToEnd();
//HttpContext.Current.Response.Write("<br/><br/>Retrieve Context: <br/>" + resultString);
}
These are full rest api URLs from config files:
<add key="GrantCodeRequest" value="https://<location>/AuthorizationServices/provider/authorize?response_type=code&state=mystateid&client_id=mVisum&redirect_uri=http://localhost:1316/RetrieveContext.aspx&scope=read"/>
<add key="AccessTokenRequest" value="https://<location>/AuthorizationServices/oauth/token?client_id=mVisum&state=mystateid&scope=read&client_secret=TESTMVISUM&response_type=token&grant_type=authorization_code&redirect_uri=http://localhost:1316/RetrieveContext.aspx"/>
<add key="RetrieveContextRequest" value="http://<location>/UserContext/rest/context/user/system/"/>
When I am doing only second request with accessToken value initialized to valid value second call is also working without any exception. This method is written in one handler.
Can any one tell me why this is happening? There is no issue in REST web service. I have also tried by using two separate web request and web response objects but nothing is working out
Try to use
WebClient client = new WebClient();
client.Headers["Content-type"] = #"application/json";
Stream data = client.OpenRead(yoururl); ;
StreamReader reader = new StreamReader(data);
string responseFromServer = reader.ReadToEnd();
The above works fine for me.