Get Access Token Using C#, Windows phone 8.1 - c#

I am trying to get the access token for the feed.Below is a code, i used to get the access token.
public async Task<string> GetAccessToken()
{
string postString = String.Format("username={0}&password={1}&grant_type=password", "userName", "pwd");
string url = "http://example.net/Token";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(postString);
try
{
HttpWebResponse webResponse = (HttpWebResponse)(await request.GetResponseAsync());
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
string result = responseStreamReader.ReadToEnd();//parse token from result
}
catch(Exception ex)
{
}
return "";
}
The error below
"An error occurred while sending the request. The text associated with this error code could not be found.
The server name or address could not be resolved"
is throwing while it executes the below code
HttpWebResponse webResponse = (HttpWebResponse)(await request.GetResponseAsync());
Please help me to solve the issue

Try this if you are using POST request
public async Task<string> GetAccessToken()
{
string postString = String.Format("username={0}&password={1}&grant_type=password", "userName", "pwd");
try
{
using (var httpClient = new HttpClient())
{
var request1 = new HttpRequestMessage(HttpMethod.Post, "FeedURL");
request1.Content = new StringContent(postString);
var response = await httpClient.SendAsync(request1);
var result1 = await response.Content.ReadAsStringAsync();
result1 = Regex.Replace(result1, "<[^>]+>", string.Empty);
var rootObject1 = JObject.Parse(result1);
string accessToken = rootObject1["access_token"].ToString();
}
}
catch (Exception ex)
{
}
}

Related

c# to get oauth2 token but get error (Remote server returns 400 Bad Request)

I am trying to use this C# to get oauth token from a website. But the below codes return '404 Bad Request' error. Is there anything wrong in my code? The website engineer says there should be a JSON file returned to show error details. How do I get that JSON file? What I can see is just 1 line error message in VS2012.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://xxxx.com/api/oauth/token");
webRequest.Method = "POST";
webRequest.AllowAutoRedirect = true;
//write the data to post request
String postData = "client_id=abc&client_secret=xxx&grant_type=client_credentials";
byte[] buffer = Encoding.Default.GetBytes(postData);
if (buffer != null)
{
webRequest.ContentLength = buffer.Length;
webRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
}
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string strResponse = reader.ReadToEnd();
I used Postman to send a request and I can get the token in its response. How should I modify my C# codes to get the token?
Can you try like this
public (string, string, string, string) GetOAuth(string CliendId, string ClientSecret, string OAuthURl)
{
using (var httpClient = new HttpClient())
{
var creds = $"client_id={CliendId}&client_secret={ClientSecret}&grant_type=client_credentials";
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var content = new StringContent(creds, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = httpClient.PostAsync(OAuthURl, content).Result;
var jsonContent = response.Content.ReadAsStringAsync().Result;
var tokenObj = JsonConvert.DeserializeObject<dynamic>(jsonContent);
var access_token = tokenObj?.access_token;
var token_type = tokenObj?.token_type;
var expires_in = tokenObj?.expires_in;
var scope = tokenObj?.scope;
return (access_token, token_type, expires_in, scope);
}
}
private void HowTOUse()
{
string access_token, token_type, expires_in, scope;
(access_token, token_type, expires_in, scope) = GetOAuth("client_id", "client_secret", "oauthurl");
}
Try using like the below code hope this code will solve the problem
private void Button_Click_1(object sender, RoutedEventArgs e)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://xxxx.com/api/oauth/token");
webRequest.Method = "POST";
webRequest.AllowAutoRedirect = true;
//write the data to post request
String postData =
"client_id=abc&client_secret=xxx&grant_type=client_credentials";
//byte[] buffer = Encoding.Default.GetBytes(postData);
//add these lines
byte[] buffer = System.Text.Encoding.ASCII.GetBytes(postData);
if (buffer != null)
{
webRequest.ContentLength = buffer.Length;
webRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
}
try
{
using (HttpWebResponse response =
(HttpWebResponse)webRequest.GetResponse())
{
using (Stream dataStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(dataStream);
string strResponse = reader.ReadToEnd();
TokenModel dt = JsonConvert.DeserializeObject<TokenModel>
(strResponse);
token = dt.accessToken;
//Assign json Token values from strResponse to model tok_val
tok_val.accessToken = dt.accessToken;
tok_val.expires_in = dt.expires_in;
tok_val.RefreshToken = dt.RefreshToken;
tok_val.tokenType = dt.tokenType;
}
}
}
catch (WebException wex)
{
error = "Request Issue: " + wex.Message;
}
catch (Exception ex)
{
error = "Issue: " + ex.Message;
}

How to fix The remote server returned an error: (403) Forbidden. dailymotion api

So I am using the Dailymotion API for uploading the video and use the code I get from the GitHub and it works perfectly but after 4 videos it gives the exception:
{"The remote server returned an error: (403) Forbidden."}
And I am getting an error in PublishVideo method
var response = request.GetResponse();
Main Code
var accessToken = GetAccessToken();
Authorize(accessToken);
Console.WriteLine("Access token is " + accessToken);
var fileToUpload = #"E:\Courses\[FreeCourseSite.com] Udemy - Entity Framework in Depth The Complete Guide\3. Building a Model using Database-First Workflow\11. Summary.mp4";
Console.WriteLine("File to upload is " + fileToUpload);
var uploadUrl = GetFileUploadUrl(accessToken);
Console.WriteLine("Posting to " + uploadUrl);
var response = GetFileUploadResponse(fileToUpload, accessToken, uploadUrl);
Console.WriteLine("Response:\n");
Console.WriteLine(response + "\n");
Console.WriteLine("Publishing video.\n");
var uploadedResponse = PublishVideo(response, accessToken);
Console.WriteLine(uploadedResponse);
Console.WriteLine("Done. Press enter to exit.");
Console.ReadLine();
}
private static UploadResponse GetFileUploadResponse(string fileToUpload, string accessToken, string uploadUrl)
{
var client = new WebClient();
client.Headers.Add("Authorization", "OAuth " + accessToken);
var responseBytes = client.UploadFile(uploadUrl, fileToUpload);
var responseString = Encoding.UTF8.GetString(responseBytes);
var response = JsonConvert.DeserializeObject<UploadResponse>(responseString);
return response;
}
private static UploadedResponse PublishVideo(UploadResponse uploadResponse, string accessToken)
{
var request = WebRequest.Create("https://api.dailymotion.com/me/videos?url=" + HttpUtility.UrlEncode(uploadResponse.url));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Authorization", "OAuth " + accessToken);
var requestString = String.Format("title={0}&tags={1}&channel={2}&private={3}&published={4}",
HttpUtility.UrlEncode("123123123"),
HttpUtility.UrlEncode("tag1"),
HttpUtility.UrlEncode("news"),
HttpUtility.UrlEncode("true"),
HttpUtility.UrlEncode("true"));
var requestBytes = Encoding.UTF8.GetBytes(requestString);
var requestStream = request.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
string responseString;
using (var reader = new StreamReader(responseStream))
{
responseString = reader.ReadToEnd();
}
var uploadedResponse = JsonConvert.DeserializeObject<UploadedResponse>(responseString);
return uploadedResponse;
}
private static string GetAccessToken()
{
var request = WebRequest.Create("https://api.dailymotion.com/oauth/token");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var requestString = String.Format("grant_type=password&client_id={0}&client_secret={1}&username={2}&password={3}",
HttpUtility.UrlEncode(SettingsProvider.Key),
HttpUtility.UrlEncode(SettingsProvider.Secret),
HttpUtility.UrlEncode(SettingsProvider.Username),
HttpUtility.UrlEncode(SettingsProvider.Password));
var requestBytes = Encoding.UTF8.GetBytes(requestString);
var requestStream = request.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
string responseString;
using (var reader = new StreamReader(responseStream))
{
responseString = reader.ReadToEnd();
}
var oauthResponse = JsonConvert.DeserializeObject<OAuthResponse>(responseString);
return oauthResponse.access_token;
}
private static void Authorize(string accessToken)
{
var authorizeUrl = String.Format("https://api.dailymotion.com/oauth/authorize?response_type=code&client_id={0}&scope=read+write+manage_videos+delete&redirect_uri={1}",
HttpUtility.UrlEncode(SettingsProvider.Key),
HttpUtility.UrlEncode(SettingsProvider.CallbackUrl));
Console.WriteLine("We need permissions to upload. Press enter to open web browser.");
Console.ReadLine();
Process.Start(authorizeUrl);
var client = new WebClient();
client.Headers.Add("Authorization", "OAuth " + accessToken);
Console.WriteLine("Press enter once you have authenticated and been redirected to your callback URL");
Console.ReadLine();
}
private static string GetFileUploadUrl(string accessToken)
{
var client = new WebClient();
client.Headers.Add("Authorization", "OAuth " + accessToken);
var urlResponse = client.DownloadString("https://api.dailymotion.com/file/upload");
var response = JsonConvert.DeserializeObject<UploadRequestResponse>(urlResponse).upload_url;
return response;
}
}
It could be related to many causes. I suggest you to catch the error and get the response stream from our API:
try{
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
string responseString;
using (var reader = new StreamReader(responseStream))
{
responseString = reader.ReadToEnd();
}
var uploadedResponse = JsonConvert.DeserializeObject<UploadedResponse>(responseString);
return uploadedResponse;
}
catch(WebException e){
var rs = e.Response.GetResponseStream();
string errorResponseString;
using (var reader = new StreamReader(rs))
{
errorResponseString = reader.ReadToEnd();
}
Console.WriteLine(errorResponseString);
return null;
}
You will get a message explaining you why your access is forbidden.
I also invite you to check our API rate limit rules which can be a cause of forbidden call: https://developer.dailymotion.com/api/#rate-limit

Xamarin Forms Json Service Insert Data

I want to add a record to the json service in my application. How can I do this via Service Url. Here is my code.
CustomerModel customer = new CustomerModel();
customer.Name = entryCompanyName.Text;
customer.Title = entryCompanyTitle.Text;
customer.PhoneNumber = entryTelephone.Text;
customer.FaxNumber = entryFax.Text;
customer.Email = entryEmail.Text;
customer.CityId = 6444;
string json = JsonConvert.SerializeObject(customer);
string sContentType = "application/json";
string path = "service url";
HttpClient Client = new HttpClient();
var task = Client.PostAsync(path, new StringContent(json.ToString(), Encoding.UTF8, sContentType));
I'm trying M. Wiśnicki's solution, but I took this error
I did not get an error when I added System.net :( Where do i make mistakes?
This worked for me
public static async Task<string> PostEntityToApi<T>(string yourMethodUrl, T yourModel)
{
try
{
if (_httpClient == null)
{
_httpClient = new HttpClient { BaseAddress = new Uri(yourWebSiteUrl) };
}
var stringContentInput = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(new Uri(yourWebSiteUrl. + apiUrl), stringContentInput);
if (!response.IsSuccessStatusCode)
{
throw new Exception(response.StatusCode.ToString());
}
var stringAsync = await response.Content.ReadAsStringAsync();
LoggingManager.Error("Received error response: " + stringAsync);
return stringAsync;
}
catch (Exception exception)
{
return null;
}
}
You can use WebRequest, this sample working for me, i use it in my app.
This is System.Net.WebRequest class, here you find doc.
public async Task<string> PostSample(object data, string uri)
{
// Create an HTTP web request using the URL:
var request = (HttpWebRequest) WebRequest.Create(new Uri(uri));
request.ContentType = "application/json";
request.Method = "POST";
var itemToSend = JsonConvert.SerializeObject(data);
using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))
{
streamWriter.Write(itemToSend);
streamWriter.Flush();
streamWriter.Dispose();
}
// Send the request to the server and wait for the response:
using (var response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (var stream = response.GetResponseStream())
{
var reader = new StreamReader(stream);
var message = JsonConvert.DeserializeObject<string>(reader.ReadToEnd());
return message;
}
}
}

Problems with HttpRequest in c# for windows phone 8.1

I want to obtain a string response of this:
public async Task<string> CheckConnection(){
//Declarations of Variables
string result = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContinueTimeout = 4000;
request.Credentials = CredentialCache.DefaultNetworkCredentials;
//Add headers to request
request.Headers["Type"] = "CHECK";
request.Headers["Device"] = "1";
request.Headers["Version"] = "0.000";
request.Headers["Os"] = "WindowsPhone";
HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
if (response.StatusCode == HttpStatusCode.OK)
{
//To obtain response body
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8);
result = streamRead.ReadToEnd();
streamRead.Dispose();
}
return result;
}
public async Task<string> SizeFit()
{
//Declarations of Variables
string result = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = CredentialCache.DefaultNetworkCredentials;
//Add headers to request
request.Headers["Type"] = "SIZEFIT";
request.Headers["Device"] = "1";
request.Headers["Version"] = "0.000";
request.Headers["Os"] = "WindowsPhone";
HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
if (response.StatusCode != null)
{
//To obtain response body
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8);
result = streamRead.ReadToEnd();
streamRead.Dispose();
}
return result;
}
When I use this general function for obtain 1 for true connect and Size, but always return 1 as syze when my zip have 4k of size...
public async Task<string> doSync()
{
//Declaration of variables
string response = await CheckConnection();
//When is 1, the checkConnection will connect then request Size of zip!
if (response == "1")
{
response = await SizeFit();
}
return response;
}
Any one can help me? Thanks in advance.
Solved! Just add:
request.Headers["Cache-Control"] = "no-cache";
request.Headers["Pragma"] = "no-cache";
This is for windows phone cache problems with httpwebrequest!

Implementing Last.fm authentication in Windows Phone 8

I need to implement last.fm authentication in my Windows Phone 8 application. Last.fm requires a POST request with https for successful login. Here is what I'm doing.
public async void GetMobileSession(string userName, string password, Action<LastFmAuthResponse> onCompletion)
{
string CORE_URL = "https://ws.audioscrobbler.com/2.0/";
var parameters = new Dictionary<string, string>();
parameters.Add("username", userName);
parameters.Add("password", password);
parameters.Add("method", "auth.getMobileSession");
parameters.Add("api_key", api_key);
string signature = GetSignature(parameters);
string comboUrl = string.Concat("method=auth.getMobileSession", "&api_key=", api_key,
"&username=", userName, "&password=", password, "&api_sig=", signature);
LastFmAuthResponse response = null;
byte[] pendingPostContent = Encoding.UTF8.GetBytes(comboUrl);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(CORE_URL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (Stream requestStream = await request.GetRequestStreamAsync())
{
await requestStream.WriteAsync(pendingPostContent, 0, pendingPostContent.Length);
}
request.BeginGetResponse(new AsyncCallback(n =>
{
HttpWebResponse rawResponse = (HttpWebResponse)request.EndGetResponse(n);
string rawData = string.Empty;
using (StreamReader reader = new StreamReader(rawResponse.GetResponseStream()))
{
rawData = reader.ReadToEnd();
}
try
{
if (!string.IsNullOrEmpty(rawData))
{
response = CommonFunctions.GetObjectFromString<LastFmAuthResponse>(rawData);
}
}
catch
{
}
onCompletion(response);
}), null);
}
However the code is failing at request.BeginGetResponse It returns an error saying remote server could not be found. Can someone please point out what I'm doing wrong here?

Categories

Resources