How to handle the 401 Error response using C#? - c#

I have a API which returns the json response.
When I call the API from Fiddler it gives me the json reponse
as shown below:
JSON Response:
Call to API from Web page:
protected void FinalCall()
{
// try
// {
string url = txtdomainURL.Text.Trim();
string apiname = txtAPIname.Text.Trim();
string apiURL = apiname+"/"+txtStoreID.Text.Trim()+"/"+txtSerialNo.Text.Trim(); //"duediligence/1/45523354232323424";// 990000552672620";//45523354232323424";
//duediligence/1/45523354232323424 HTTP/1.1
string storeID = txtStoreID.Text.Trim();//Test Store ID:1 Live Store ID: 2
string partnerID = txtPartnerID.Text.Trim();// "1";
string scretKey = txtSecretKey.Text.Trim();// "234623ger787qws3423";
string requestBody = txtRequestBody.Text.Trim(); //"{\"category\": 8}";
string data = scretKey + requestBody;
string signatureHash = SHA1HashStringForUTF8String(data);
lblSignatureHash.Text = signatureHash;
String userName = partnerID;
String passWord = signatureHash;
string credentials = userName + ":" + passWord;//Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
var dataString = JsonConvert.SerializeObject(requestBody); //JsonConvert.SerializeObject(requestBody);
var bytes = Encoding.Default.GetBytes(dataString);
WebClient client = new WebClient();
string base64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
client.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
lblBase64.Text = base64;
client.Headers.Add(HttpRequestHeader.Accept, "application/json");
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
//string response = cli.UploadString(url + apiURL, dataString); //"{some:\"json data\"}"
string completeURLRequest = url + apiURL;
//I GET ERROR HERE
var result = client.DownloadString(completeURLRequest);
//CODE below this line is not executed
//Context.Response.TrySkipIisCustomErrors = true;
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonObject = serializer.DeserializeObject(result.ToString());
//var result1 = client.UploadData(completeURLRequest, "POST", bytes);
Response.Write(result);
txtwebresponse.Text = jsonObject.ToString();
//}
Now, When the same is executed from a web page it throws exeception '401 Unauthorized Exception'. So, instead of showing error page I want to read the returned JSON error response (as in fiddler) and show to user.
Help Appreciated!

Adapted from this answer to ".Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned" by Jon Skeet:
try
{
using (WebResponse response = request.GetResponse())
{
Console.WriteLine("You will get error, if not do the proper processing");
}
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse) response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
// text is the response body
string text = reader.ReadToEnd();
}
}
}

Slightly changing SilentTremor's answer. Combining the using statements makes the code a little bit shorter.
catch (WebException ex)
{
HttpWebResponse httpResponse = (HttpWebResponse)ex.Response;
using (WebResponse response = ex.Response)
using (Stream data = response.GetResponseStream())
using (StreamReader reader = new StreamReader(data))
{
string errorMessage = reader.ReadToEnd();
}
}

Related

Invalid Client Authorization header when trying to get token from "Here" REST API

I am trying to get a Bearer token to start using HERE REST API,
using (OAuth 2.0 (JSON Web Tokens))
after a lot of struggles, I am stuck with 401202 error:
{"errorId":"ERROR-e0242f30-05da-4df0-9beb-b697062240ce","httpStatus":401,"errorCode":401202,"message":"Invalid
Client Authorization header, expecting signed request
format.","error":"invalid_request","error_description":"errorCode:
'401202'. Invalid Client Authorization header, expecting signed
request format."}
Here is my code:
private void GetToken()
{
try
{
var here_client_id = "b1Ibl7XXXXXXXoZtNKb";
var here_access_key_id = "8DKjlwXXXXXXXXXerGCXPA";
var here_access_key_secret = "tuU-bGMa1ljancfoXXXXXXXXXXXXXXXK8cMlk4o0EGUpS2fmwkAtlltFPDhYQUgytJLL-X_YNIjmdWcOabQ";
var url = "https://account.api.here.com/oauth2/token";
var Parameters = "grant_type=client_credentials&client_id=" + here_client_id + "&oauth_consumer_key=" + here_access_key_secret;
var hmac = new HMACSHA256();
var key = Convert.ToBase64String(hmac.Key);
Guid id = Guid.NewGuid();
// Create a request for the URL.
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var cred = #"OAuth oauth_consumer_key=" + here_access_key_id;
request.Headers.Add("Authorization", cred);
//request.Headers.Add("oauth_consumer_key", here_access_key_id);
request.Headers.Add("oauth_nonce", id.ToString());
request.Headers.Add("oauth_signature_method", "HMAC-SHA256");
request.Headers.Add("oauth_signature", key);
request.Headers.Add("oauth_timestamp", ConvertToUnixTimestamp(DateTime.Now).ToString());
request.Headers.Add("oauth_version", "1.0");
byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
request.ContentLength = byteArray.Length;
Stream postStream = request.GetRequestStream();
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
MessageBox.Show(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
//MessageBox.Show(reader.ReadToEnd());
textBox1.Text = reader.ReadToEnd();
}
}
}
This is my first cut and is rough but.
var accessKey = "";
var secret = "";
var url = "https://account.api.here.com/oauth2/token";
var nonce = GetNonce();
var timestamp = GetTimeStamp();
var baseString = #"grant_type=client_credentials&oauth_consumer_key=" + accessKey + "&oauth_nonce=" + nonce + "&oauth_signature_method=HMAC-SHA256&oauth_timestamp=" + timestamp + "&oauth_version=1.0";
var workingString = new List<string>();
foreach (var parameter in baseString.Split('&').ToList())
{
workingString.Add(Uri.EscapeDataString(parameter.Split('=')[0] + "=" + parameter.Split('=')[1].Trim()));
}
var urlEncodeParamaterString = String.Join(Uri.EscapeDataString("&"), workingString.ToArray());
var fullBaseString = $"POST&{Uri.EscapeDataString(url)}&{urlEncodeParamaterString}";
var signature = CreateToken(fullBaseString, (Uri.EscapeDataString(secret) + "&"));
var authHeader = "OAuth oauth_consumer_key=\"" + accessKey + "\",oauth_signature_method=\"HMAC-SHA256\",oauth_timestamp=\"" + timestamp + "\",oauth_nonce=\"" + nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + Uri.EscapeDataString(signature) + "\"";
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Authorization", authHeader);
var response = await httpClient.PostAsync(url, new StringContent($"grant_type={Uri.EscapeDataString("client_credentials")}",
Encoding.UTF8,
"application/x-www-form-urlencoded"));
var responseContent = response.Content.ReadAsStringAsync();
}
The other Methods are
private string GetNonce()
{
var rand = new Random();
var nonce = rand.Next(1000000000);
return nonce.ToString();
}
private string CreateToken(string message, string secret)
{
secret = secret ?? "";
var encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(secret);
byte[] messageBytes = encoding.GetBytes(message);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
return Convert.ToBase64String(hashmessage);
}
}
private string GetTimeStamp()
{
var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
At the end I did it without web JSON WEB TOKENS.
According to this API documentation the call was made only with API KEY.
public static string ConvertAddressToCoordinate(string address)
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var apikey = "xxxxxxxxxxxxxxxxxxxxx_xxxxxxxxx";
var url = "https://geocoder.ls.hereapi.com/6.2/geocode.json?apiKey=";
var fullurl = url + apikey + "&searchtext=" + address;
// Create a request for the URL.
WebRequest request = WebRequest.Create(fullurl);
request.Method = "GET";
request.ContentType = "application/json";
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
return responseFromServer;
}
catch (WebException ex)
{
return "ERROR " + ex.Message;
}
catch (Exception ex)
{
return "ERROR " + ex.Message;
}
}

POST or Get Request with Json response in C# windows Form App

I made an API in server side with PHP + Laravel framework which accept both GET & Post requests with some special parameters.
It's address is : http://beresun.ir/API/Orders/0
and it gets these parameters :
token > string ,
restaurant_id > integer ,
admin_id > integer ,
token_id > integer .
if we send a request with GET method with these parameters, for example it will be :
http://beresun.ir/API/Orders/0?token=2JEuksuv86DcFmLrQa7nna4QDeowuGTqpyUK0pf9wSlbe6D5hLtEVxvzMT5gAZG0xBKy00HxS3J79mcr8F54dBD0uIg5HX5fzPOAP&restaurant_id=1&admin_id=2&token_id=40 which returns a json data , you can click on the link to see the results .
the response json data includes some information about customers and it's products.
now I want to make a windows application for this service with C# and request data from this API with POST or GET methods :
I want to use this API to get Json data from Web server and save them in my Windows application , So I created two functions in one of my Form Classes :
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
public partial class MainActivity : Form
{
string token = "2JEuksuv86DcFmLrQa7nna4QDeowuGTqpyUK0pf9wSlbe6D5hLtEVxvzMT5gAZG0xBKy00HxS3J79mcr8F54dBD0uIg5HX5fzPOAP";
int restaurant_id = 1;
int admin_id = 2;
int token_id = 40;
private void SendWebrequest_Get_Method()
{
try
{
String postData = "token=" + token +
"&restaurant_id=" + restaurant_id +
"&admin_id=" + admin_id +
"&token_id=" + token_id;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://beresun.ir/API/Orders/0?" + postData);
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json";
request.Method = WebRequestMethods.Http.Get;
WebResponse response = request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
String json_text = sr.ReadToEnd();
dynamic stuff = JsonConvert.DeserializeObject(json_text);
if (stuff.error != null)
{
MessageBox.Show("problem with getting data", "Error");
}
else
{
MessageBox.Show(json_text, "success");
}
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show("Wrong request ! " + ex.Message, "Error");
}
}
private void SendWebrequest_POST_Method()
{
try
{
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://beresun.ir/API/Orders/5");
// Set the Method property of the request to POST.
request.Method = "POST";
request.Credentials = CredentialCache.DefaultCredentials;
((HttpWebRequest)request).UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
// Create POST data and convert it to a byte array.
string postData = "token=" + token +
"&restaurant_id=" + restaurant_id +
"&admin_id=" + admin_id +
"&token_id=" + token_id;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json; charset=utf-8";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
MessageBox.Show(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
MessageBox.Show(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show("Wrong request ! " + ex.Message, "Error");
}
}
}
Now Here is the problem , when I test the API it works fine , but when I request data from my application , it returns error and not working .
Can anyone explain me how I should request data from this API , to get data , I searched a lot , and I used many different methods , but none of them worked for me . maybe because this API returns very much Json data or maybe request timeout happen. I don't know , I couldn't find the problem . So I asked it Here.
I don't know what I should do .
Thanks
Oki so i run your code :
private string TestURL = "http://beresun.ir/API/";
string token = "2JEuksuv86DcFmLrQa7nna4QDeowuGTqpyUK0pf9wSlbe6D5hLtEVxvzMT5gAZG0xBKy00HxS3J79mcr8F54dBD0uIg5HX5fzPOAP";
int restaurant_id = 1;
int admin_id = 2;
int token_id = 40;
public async Task<string> test()
{
try
{
using (var Client = new HttpClient())
{
Client.BaseAddress = new Uri(TestURL);
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
string postData = "token=" + token +
"&restaurant_id=" + restaurant_id +
"&admin_id=" + admin_id +
"&token_id=" + token_id;
HttpResponseMessage responce = await Client.GetAsync("Orders/0?" + postData);
if (responce.IsSuccessStatusCode)
{
var Json = await responce.Content.ReadAsStringAsync();
// !
return Json;
}
else
{
// deal with error or here ...
return null;
}
}
}
catch (Exception e)
{
return null;
}
}
and its working am getting the json file ,, i think your mistake is in postData is string Not String ! a simple type can amazing harm !
try this:
private string URL = "Your Base domain URL";
public async Task<YourModel> getRequest()
{
using (var Client = new HttpClient())
{
Client.BaseAddress = new Uri(URL);
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage responce = await Client.GetAsync("Your Method or the API you callig");
if (responce.IsSuccessStatusCode)
{
var Json = await responce.Content.ReadAsStringAsync();
var Items= JsonConvert.DeserializeObject<YourModel>(Json);
// now use you have the date on Items !
return Items;
}
else
{
// deal with error or here ...
return null;
}
}
}

Unable to Post on Pinterest using their API

I'm receiving a 400 Bad Request error message when posting a pin on Pinterest. It works using Postman, but doesn't work programmatically. Using C#, has anyone been able to successfully post a pin on Pinterest without using the pinsharp wrapper?
private void postPinterest(string messages, string id, string usertoken, string image, string boardname, string username)
{
string link = null;
boardname = boardname.Replace(" ", "-");
string board = username + "/" + boardname;
string url = "https://api.pinterest.com/v1/pins?access_token=" + usertoken;
StringBuilder sb = new StringBuilder();
if (!string.IsNullOrEmpty(board))
sb.Append("&board=" + HttpUtility.UrlEncode(board));
if (!string.IsNullOrEmpty(messages))
sb.Append("&note=" + HttpUtility.UrlEncode(messages));
if (!string.IsNullOrEmpty(link))
sb.Append("&image_url=" + HttpUtility.UrlEncode(link));
string postdata = sb.ToString().Substring(1);
PostData(url, postdata);
}
private object PostData(string url, string postdata)
{
object json=null;
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
// req.Accept = "application/json";
using (var stream = req.GetRequestStream())
{
byte[] bindata = Encoding.ASCII.GetBytes(postdata);
stream.Write(bindata, 0, bindata.Length);
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
string response = new StreamReader(resp.GetResponseStream()).ReadToEnd();
json = JsonConvert.DeserializeObject<dynamic>(response);
return json;
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
string error = reader.ReadToEnd();
return json;
}
}
}
}
return json;
}
EDIT:
It doesn't work using the JSON format or x-www-form-urlencoded format.
I changed the content type to application/x-www-form-urlencoded and now I'm receiving the error message below. I receive 400 Bad Request error using JSON format:
"{\n \"message\": \"405: Method Not Allowed\",\n \"type\": \"http\"\n}"
The problem is the the parameter that you are posting.
In the Api i could find board as a parameter but both note and image comes under field parameter which specifies the return type JSON.
As per documentation on this page you can post in this format
https://api.pinterest.com/v1/boards/anapinskywalker/wanderlust/pins/?
access_token=abcde&
limit=2&
fields=id,link,counts,note
So I tried the following and its getting response
https://api.pinterest.com/v1/boards/?access_token="YourTokenWithoutQuotes"&fields=id%2Ccreator
Would suggest you to first test the Api you are hitting putting a breakpoint inside the PostData function and check if the passed url is in the correct format and compare it with Pininterest API Explorer.
As you might have already received authorization code and access token so I am assuming your post function should be working fine.
public string postPinterest(string access_token,string boardname,string note,string image_url)
{
public string pinSharesEndPoint = "https://api.pinterest.com/v1/pins/?access_token={0}";
var requestUrl = String.Format(pinSharesEndPoint, accessToken);
var message = new
{
board = boardname,
note = note,
image_url = image_url
};
var requestJson = new JavaScriptSerializer().Serialize(message);
var client = new WebClient();
var requestHeaders = new NameValueCollection
{
{"Content-Type", "application/json" },
{"x-li-format", "json" }
};
client.Headers.Add(requestHeaders);
var responseJson = client.UploadString(requestUrl, "POST", requestJson);
var response = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(responseJson);
return response;
}

HttpWebRequest method GET/POST not working?

I am working with GoogleApi. I want to get accesstoken as response using Google api. when I am sending httpwebrequest for getting access token then
When I used :- request.Method = "POST"
Exception:- HTTP method POST is not supported by this URL
When I used :- request.Method = "GET"
Exception:- System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type
The actual request might look like:
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code
A successful response is returned as a JSON array, similar to the following:
{
"access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in":3920,
"token_type":"Bearer"
}
My Code is :-
var request = (HttpWebRequest)WebRequest.Create(#"https://accounts.google.com");
request.Method = "POST";
request.ContentType = "application/json";
//request.KeepAlive = false;
// request.Headers[HttpRequestHeader.Authorization] = "";
//request.ContentLength = 0;
using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"code\":\"4/M1IIC8htCuvYORuVJK16oadDb3Gd.cigIKgaPjvUYXE-sT2ZLcbSrckCLgwI\"," + "\"client_id\":\"841994137170.apps.googleusercontent.com\"," + "\"client_secret\":\"MXjKvevD_cKp5eQWZ1RFXfdo\"," + "\"redirect_uri\":\"http://gmailcheck.com/response.aspx\"," + "\"grant_type\":\"authorization_code\"}";
streamWriter.Write(json);
// streamWriter.Flush();
//streamWriter.Close();
}
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
StreamReader responsereader = new StreamReader(response.GetResponseStream());
var responsedata = responsereader.ReadToEnd();
//Session["responseinfo"] = responsereader;
}
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
var httpResponse = (HttpWebResponse)response;
using (Stream data = response.GetResponseStream())
{
var sr = new StreamReader(data);
throw new Exception(sr.ReadToEnd());
}
}
}
This is the problem:
var request = (HttpWebRequest)WebRequest.Create(#"https://accounts.google.com");
That's not the URL you showed originally. That's just the domain root. You need:
var request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
I've removed the # as your string doesn't include any line breaks or backslashes, so there's no benefit in using a verbatim string literal.
(Additionally, I'd expect this to be covered in the Google Client APIs - is it not?)

oauth/token returns empty body

I am encountering a problem getting the access_token in client application using oauth.
The returned response has empty body though in API I can see the response is not empty.
tokenresponse = {
"access_token":"[ACCESSTOKENVALUE]",
"token_type":"bearer",
"expires_in":"1200",
"refresh_token":"[REFRESHTOKENVALUE]",
"scope":"[SCOPEVALUE]"
}
The method from API that returns the token http://api.sample.com/OAuth/Token:
public ActionResult Token()
{
OutgoingWebResponse response =
this.AuthorizationServer.HandleTokenRequest(this.Request);
string tokenresponse = string.Format("Token({0})", response!=null?response.Body:""));
return response.AsActionResult();
}
The client method that requests the token is:
public string GetAuthorizationToken(string code)
{
string Url = ServerPath + "OAuth/Token";
string redirect_uri_encode = UrlEncode(ClientPath);
string param = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",code, ClientId, ClientSecret, redirect_uri_encode);
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
request.Headers.Remove(HttpRequestHeader.Cookie);
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
if (!string.IsNullOrEmpty(result))
{
TokenData tokendata = JsonConvert.DeserializeObject<TokenData>(result);
return UpdateAuthorizotionFromToken(tokendata);
}
return null;
}
The result variable is empty.
Please let me know if you have any idea what could cause this. Initially I assumed is because of the cookies so I tried to remove them from request.
Thanks in advance.
Dear just create webclient using following code and you will get json info in tokeninfo.I used it and simply its working perfect.
WebClient client = new WebClient();
string postData = "client_id=" + ""
+ "&client_secret=" + ""
+ "&grant_type=password&username=" + "" //your username
+ "&password=" + "";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
You can then use substring that contains only token from tokeninfo.
To upload tracks on sound cloud.
private void TestSoundCloudupload()
{
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(Server.MapPath("Downloads//0.mp3"), "track[asset_data]", "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "Some title");
form.Add("track[sharing]", "public");
form.Add("oauth_token", "");
form.Add("format", "json");
form.Add("Filename", "0.mp3");
form.Add("Upload", "Submit Query");
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
Response.Write(reader.ReadToEnd());
}
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}

Categories