I am developing a C# console application to extract data from a PHP website. The website has both a public view and an extended view for logged in users. I am able to use my credentials, my username and password, to log in to the site via FireFox, Edge, and ID and view the additional material successfully. The parsing of the public data is not a problem, but the issue lies in extraction of the extended data.
I have tried using a variety of methods to create cookies based on my login credentials in order to access the extended view. My logic behind this is so: there is a login php page with a username and password. After successfully logging in, each subsequent access to a public page will display additional information (the extended data) if you are logged in.
I am trying to either pass my credentials via as part of the cookie container in the httpwebrequest or copy my existing cookies from firefox (after logging in) to my cookie container for my httpwebrequest. After that, I would use a HttpWebResponse object to view the returned data stream. It is there I should be able to identify the extended data in the html. However, to my knowledge, it has just returned the public view instead.
I am able to open the firefox cookies successfully but I don't know if they are being used successfully in the CookieContainer
//!!!!Firefox cookie method!!!!//
CookieContainer ffCookieContainer = new CookieContainer();
Cookie ffCookie = new Cookie();
bool fRtn = false;
string strPath, strTemp, strDb, strHost, strField, Value;
strPath = #"C:\Documents and Settings\YourUserName\Application Data\Mozilla\Firefox\Profiles\urq2tlhr.default\cookies.sqlite";
strDb = "Data Source=" + strPath;
// Now open the temporary cookie jar and extract Value from the cookie if we find it.
using (SqliteConnection conn = new SqliteConnection())
{
using (SqliteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT host, name, value, path, expiry, isSecure, isHttpOnly, lastAccessed, id FROM moz_cookies;";
conn.ConnectionString = strDb;
conn.Open();
using (SqliteDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Value = reader.GetString(0) + " " + reader.GetString(1) + " " + reader.GetString(2) + " " + reader.GetString(3) + " " + reader.GetString(4) + " " + reader.GetString(5) + " " + reader.GetString(6) + " " + reader.GetString(7) + " " + reader.GetString(8);
if (!Value.Equals(string.Empty))
{
//fRtn = true;
//break;
try
{
ffCookie.Discard = false;
ffCookie.Expired = false;
ffCookie.Domain = reader.GetString(0);
ffCookie.Expires = Convert.ToDateTime("01/01/2025");
ffCookie.Domain = reader.GetString(0);
ffCookie.HttpOnly = false;
ffCookie.Secure = false;
ffCookie.Port = "";
ffCookie.Name = reader.GetString(1);
ffCookie.Path = reader.GetString(3);
ffCookie.Value = reader.GetString(2);
Console.WriteLine(Value);
ffCookieContainer.Add(ffCookie);
}
catch (Exception)
{
}
}
}
}
conn.Close();
}
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("website/view");
request.CookieContainer = ffCookieContainer;
//SECOND METHOD creating cookies based on credentials
string parameters = "username=blah#domain.com&password=blah";
string userName = "blah#domain.com";
string password = "blah";
string url = "example.com/index.php?forcelogin=1";
HttpWebRequest requestTwo = (HttpWebRequest)WebRequest.Create(url);
requestTwo.Method = "POST";
requestTwo.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
requestTwo.Headers.Add("Accept-Encoding: gzip,deflate");
requestTwo.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
requestTwo.KeepAlive = true;
requestTwo.Headers.Add("Keep-Alive: 900");
requestTwo.Referer = "example.com/index.php?forcelogin=1";
requestTwo.ContentLength = parameters.Length;
requestTwo.ContentType = "application/x-www-form-urlencoded";
requestTwo.CookieContainer = new CookieContainer();
using (Stream stream = requestTwo.GetRequestStream())
{
byte[] paramAsBytes = Encoding.Default.GetBytes(parameters);
stream.Write(paramAsBytes, 0, paramAsBytes.Count());
}
CookieContainer myContainer = new CookieContainer();
using (HttpWebResponse responseTwo = (HttpWebResponse)requestTwo.GetResponse())
{
foreach (var cookie in responseTwo.Cookies)
{
var properties = cookie.GetType()
.GetProperties()
.Select(p => new
{
Name = p.Name,
Value = p.GetValue(cookie)
});
foreach (var property in properties)
{
Console.WriteLine("{0}: {1}", property.Name, property.Value);
}
}
myContainer = requestTwo.CookieContainer;
}
//repeat the cookie reassignment to the web request for the public view of the web page
//READ THE RESPONSE
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == null)
readStream = new StreamReader(receiveStream);
else
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
string data = readStream.ReadToEnd();
response.Close();
readStream.Close();
}
I expect to be able to see a newly generated html value in the page get response but I don't see it.
Related
[HTTPWEBREQUEST 1]https://1drv.ms/u/s!AtL5uCkGy1ERgbEWHlNApMtROuP_0Q
[HTTPWEBREQUEST 2]https://1drv.ms/u/s!AtL5uCkGy1ERgbEXlHjqHdho3lUjfw
When I am trying to call withing main for second time a HttpWebRequest1 and the nested HttpWebRequest2, it runs fine. But on the second run of the nested HttpWebRequest2 I get an exception on THIS line(System.IO.StreamReader sr2 = new System.IO.StreamReader(s2)) on its second run.
Exception:> "Message = "Stream was not readable."
try
{
HttpWebRequest WebRequestObjectCards = (HttpWebRequest)HttpWebRequest.Create("https://api.ucy.ac.cy/api/v1/cards?status=Valid&");
HttpWebRequest WebRequestObjectUsers = (HttpWebRequest)HttpWebRequest.Create("https://api.ucy.ac.cy/api/v1/users/" + ucy_id);
if (WebRequestObjectCards != null && WebRequestObjectUsers != null)
{
WebRequestObjectCards.Method = "GET";
WebRequestObjectCards.Timeout = 12000;
WebRequestObjectCards.ContentType = "application/json";
WebRequestObjectCards.Headers.Add("Authorization", "Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
WebRequestObjectCards.KeepAlive = true;
WebRequestObjectUsers.Method = "GET";
WebRequestObjectUsers.Timeout = 12000;
WebRequestObjectUsers.ContentType = "application/json";
WebRequestObjectUsers.Headers.Add("Authorization", "Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
WebRequestObjectUsers.KeepAlive = true;
using (System.IO.Stream s = WebRequestObjectCards.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
var serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue; // The value of this constant is 2,147,483,647
Students UCYstudents = serializer.Deserialize<Students>(jsonResponse);
//String to be added in csv
var csv = new StringBuilder();
//prepare CSV Header
newLine = string.Format("***StartOfFile***");
csv.AppendLine(newLine);
newLine = string.Format("ID; FirstName; LastName; RFIDUID; PrintedCardNumber; ValidUntil; Enabled; email; group ");
csv.AppendLine(newLine);
//deserialize JSON to CSV
foreach (var item in UCYstudents.data)
{
if (item.ucy_id != null)
{
ucy_id = item.ucy_id;// used as parameter for WebRequestObjectUsers
ID = item.ucy_id.ToString().TrimStart('0');
RFIDUID = item.card_number.ToString().TrimStart('0');
PrintedCardNumber = item.card_number.ToString().TrimStart('0');
if (item.expiration_date != null)
{
ValidUntil = item.expiration_date.ToString().Replace("-30","-01");
dt = Convert.ToDateTime(ValidUntil);
ValidUntil = ("" + dt.Day + "." + dt.Month + "." + dt.Year);
}
else
{
ValidUntil = "";
}
Enabled = "TRUE";
//Getting response from WebRequestObjectUsers
using (System.IO.Stream s2 = WebRequestObjectUsers.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr2 = new System.IO.StreamReader(s2))
{
serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue; // The value of this constant is 2,147,483,647
jsonResponse = sr2.ReadToEnd();
Users UCYUser = serializer.Deserialize<Users>(jsonResponse);
FirstName = UCYUser.data.name_en.ToString();
LastName = UCYUser.data.surname_en.ToString();
email = UCYUser.data.mail.ToString();
group = "1";
//Write Fields to CSV File
newLine = string.Format("{0};{1};{2};{3};{4};{5};{6};{7};{8}", ID, FirstName, LastName, RFIDUID, PrintedCardNumber, ValidUntil, Enabled, email, group);
csv.AppendLine(newLine);
ID = "";
FirstName = "";
LastName = "";
RFIDUID = "";
PrintedCardNumber = "";
ValidUntil = "";
email = "";
group = "";
sr2.Close();
}
}
}
}
File.WriteAllText(#".\export.csv", csv.ToString(), Encoding.UTF8);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
The two HttpWebRequest objects you create are different instances of the class; you don't need to close or reset one while using the other.
If the API is following conventions, then the 401 error means exactly what the message says: the server doesn't think the second request is authorized to access that endpoint. Maybe the server has different permissions required to get the list of users. The server identifies the request and permissions through the Authorization: Bearer token that you are sending. Look at other ways to test that token and request data from that endpoint.
I'm trying to create a .NET web application integration with RTC, where I would insert new workitems using RTC change management services, as defined in this article (specifically in "Create a Change Request"). I was able to get the URL-to-be-used inside services.xml file (/oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/) and my goal is to insert data using JSON.
My code is basically the following:
CookieContainer cookies = new CookieContainer();
HttpWebRequest documentPost = (HttpWebRequest)WebRequest.Create(rtcServerUrl + "/oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/order");//"Order" is the workitem name
documentPost.Method = "POST";
documentPost.CookieContainer = cookies;
documentPost.Accept = "application/json";
documentPost.ContentType = "application/x-oslc-cm-change-request+json";
documentPost.Timeout = TIMEOUT_SERVICO;
string json = "{ \"dc:title\":\"" + title + "\", \"rtc_cm:filedAgainst\": [ { \"rdf:resource\" : \"" + rtcServerUrl + "/resource/itemOid/com.ibm.team.workitem.Category/" + idCategory + "\"} ] }"; //dc:title and rtc_cm:filedAgainst are the only two mandatory data from the workitem I'm trying to create
using (var writer = new StreamWriter(documentPost.GetRequestStream()))
{
writer.Write(json);
writer.Flush();
writer.Close();
}
Encoding encode = System.Text.Encoding.UTF8;
string retorno = null;
//Login
HttpWebRequest formPost = (HttpWebRequest)WebRequest.Create(rtcServerUrl + "/j_security_check");
formPost.Method = "POST";
formPost.Timeout = TIMEOUT_REQUEST;
formPost.CookieContainer = request.CookieContainer;
formPost.Accept = "text/xml";
formPost.ContentType = "application/x-www-form-urlencoded";
String authString = "j_username=" + userName + "&j_password=" + password; //create authentication string
Byte[] outBuffer = System.Text.Encoding.UTF8.GetBytes(authString); //store in byte buffer
formPost.ContentLength = outBuffer.Length;
System.IO.Stream str = formPost.GetRequestStream();
str.Write(outBuffer, 0, outBuffer.Length); //update form
str.Close();
//FormBasedAuth Step2:submit the login form and get the response from the server
HttpWebResponse formResponse = (HttpWebResponse)formPost.GetResponse();
var rtcAuthHeader = formResponse.Headers["X-com-ibm-team-repository-web- auth-msg"];
//check if authentication has failed
if ((rtcAuthHeader != null) && rtcAuthHeader.Equals("authfailed"))
{
//authentication failed. You can write code to handle the authentication failure.
//if (DEBUG) Console.WriteLine("Authentication Failure");
}
else
{
//login successful
HttpWebResponse responseRetorno = (HttpWebResponse)request.GetResponse();
if (responseRetorno.StatusCode != HttpStatusCode.OK)
retorno = responseRetorno.StatusDescription;
else
{
StreamReader reader = new StreamReader(responseRetorno.GetResponseStream());
retorno = "[Response] " + reader.ReadToEnd();
}
responseRetorno.Close();
formResponse.GetResponseStream().Flush();
formResponse.Close();
}
As I was managed to search for in other forums, this should be enough in order to create the workitem (I have a very similar code working to update workitems using "" URL and PUT method). However, instead of create the workitem in RTC and give me some response with item's identifier, the request's response returns a huge JSON file that ends with "oslc_cm:next":"https:///oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/%7B0%7D?oslc_cm.pageSize=50&_resultToken=_AAY50FEkEee1V4u7RUQSjA&_startIndex=50. It's a JSON representation of the XML I receive when I access /oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/ directly from browser, like I was trying to do a simple query inside the workitem's collection (even though I'm using POST, not GET).
I also tried to use PUT method, but then I receive a 405 status code.
Does anyone have an idea of what am I missing here? My approach is wrong, even though with the same approach I'm able to update existing workitem data in RTC?
Thanks in advance.
So I'm making a small application for a vbulleting site but need to authenticate the user when he opens my application, I have code to send login request, but I am unsure how to actually check if the login was successful.
This is what I have so far:
public string Login(string username, string password)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(MPGHLogin);
string cookie = "";
string values = "vb_login_username=" + username + "&vb_login_password=" + password
+ "&securitytoken=guest&"
+ "cookieuser=checked&"
+ "do=login";
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = values.Length;
CookieContainer a = new CookieContainer();
req.CookieContainer = a;
System.Net.ServicePointManager.Expect100Continue = false;
using (StreamWriter writer = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
{
writer.Write(values);
}
HttpWebResponse c = (HttpWebResponse)req.GetResponse();
foreach (Cookie cook in c.Cookies)
{
cookie = cookie + cook.ToString() + ";";
}
if (c.StatusCode != HttpStatusCode.OK)
return "FAILED_CONNECTION";
return cookie;
}
But how can I check if the authentication was successful?
For other people that may have the same problem, I completely forgot about checking the respone stream for a login successful message, so below is the full code.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(MPGHLogin);
req.AllowAutoRedirect = true;
string cookie = "";
string values = "vb_login_username=" + username + "&vb_login_password=" + password
+ "&securitytoken=guest&"
+ "cookieuser=checked&"
+ "do=login";
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = values.Length;
CookieContainer a = new CookieContainer();
req.CookieContainer = a;
System.Net.ServicePointManager.Expect100Continue = false;
StreamWriter writer = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
writer.Write(values);
writer.Close();
req.Timeout = 5000;
HttpWebResponse c;
try {
c = (HttpWebResponse)req.GetResponse(); // da response
} catch(Exception e)
{
MessageBox.Show(e.Message, "Web Exception");
return "WebException";
}
foreach (Cookie cook in c.Cookies)
{
cookie = cookie + cook.ToString() + ";";
}
Stream resp = c.GetResponseStream();
StreamReader reader = new StreamReader(resp, Encoding.GetEncoding(c.CharacterSet));
string response = reader.ReadToEnd();
reader.Close();
reader.Dispose();
if (response.Contains("Thank you for logging in, " + username))
{
c.Dispose();
return cookie;
}
else
return "FAILED_AUTH";
I created a C# app that makes GET/POST requests to the Facebook Graph API for automating the uploading of images to a pages timeline.
The app is a console application so user logins are a no-go in terms of logging into facebook to retrieve a access token, instead i used the Graph API to generate the token and my application extends it.
This worked fine for approx 12 hours, until now all the permissions are wrong.
When i generate the token in the Graph Explorer, i select the "manage_pages", publish_pages" & "publish_actions" permissions. If use the Graph explorer to do a GET request to https://graph.facebook.com/v2.3/debug_token with the Key I get the three permissions i selected, plus a "public_profile" permission and all seems well.
When i run this in my app and the C# code runs a GET request to https://graph.facebook.com/v2.3/debug_token using the same access token i did for query, however using the applications own access key that it generates at run time to authenticate against, the only permission i get is "public_profile", even though a GET request to https://graph.facebook.com/v2.3/" + PageID + "/?fields=can_post returns that the access key CAN be used for posting, yet when i attempt to post i am given the error that i am missing the 3 key permissions i selected in the first place.
What is happening?
For reference, here are the functions i am using;
//THIS IS THE FUNCTION USED TO CHECK IF THE TOKEN IS VALID
static bool checkValidToken(string inputToken)
{
string url = "https://graph.facebook.com/v2.3/debug_token?input_token=" + inputToken + "&access_token=" + getAppAccessToken();
WebRequest wrGETURL = WebRequest.Create(url);
Stream objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string jsonResponse = objReader.ReadToEnd();
JObject resonse = (JObject)JObject.Parse(jsonResponse).GetValue("data");
return (bool)resonse.GetValue("is_valid");
}
//THIS IS USED TO CHECK IF THE TOKEN CAN BE USED TO POST TO PAGE
static bool checkCanPost(string inputToken)
{
WebRequest wrGETURL = WebRequest.Create("https://graph.facebook.com/v2.3/" + PageID + "/?fields=can_post&access_token=" + inputToken);
Stream objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string jsonResponse = objReader.ReadToEnd();
JObject resonse = (JObject)JObject.Parse(jsonResponse);
return (bool)resonse.GetValue("can_post");
}
//USED TO CALCULATE THE EXPIRY DATE ON THE TOKEN
static DateTime getExpiryDate(string inputToken)
{
WebRequest wrGETURL = WebRequest.Create("https://graph.facebook.com/v2.3/debug_token?input_token=" + inputToken + "&access_token=" + getAppAccessToken());
Stream objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string jsonResponse = objReader.ReadToEnd();
JObject resonse = (JObject)JObject.Parse(jsonResponse).GetValue("data");
DateTime expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local).AddSeconds((int)resonse.GetValue("expires_at"));
if ((int)resonse.GetValue("expires_at") == 0)
{
expires = DateTime.UtcNow.AddMonths(2);
}
return expires;
}
//USED TO GENERATE THE APP ACCESS TOKEN
static string getAppAccessToken()
{
WebRequest wrGETURL = WebRequest.Create("https://graph.facebook.com/v2.3/oauth/access_token?client_id=" + AppID + "&client_secret=" + AppSecret + "&grant_type=client_credentials");
Stream objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string jsonResponse = objReader.ReadToEnd();
JObject resonse = JObject.Parse(jsonResponse);
return (string)resonse.GetValue("access_token");
}
//USED TO EXTEND AN EXISTING TOKEN
static string extendToken(string inputToken)
{
WebRequest wrGETURL = WebRequest.Create("https://graph.facebook.com/v2.3/oauth/access_token?grant_type=fb_exchange_token&client_id=" + AppID + "&client_secret=" + AppSecret + "&fb_exchange_token=" + inputToken);
Stream objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string jsonResponse = objReader.ReadToEnd();
JObject resonse = JObject.Parse(jsonResponse);
Console.WriteLine(jsonResponse);
return (string)resonse.GetValue("access_token");
}
//USED TO GENERATE A TOKEN FOR POSTING AS THE PAGE, RATHER THAN TO THE PAGE
static string getPageToken(string inputToken)
{
WebRequest wrGETURL = WebRequest.Create("https://graph.facebook.com/v2.3/"+PageID+"?fields=access_token&access_token="+inputToken);
Stream objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string jsonResponse = objReader.ReadToEnd();
JObject resonse = JObject.Parse(jsonResponse);
return (string)resonse.GetValue("access_token");
}
//FUNCTION FOR GETTING ALL PERMISSIONS FOR A TOKEN
static List<string> getTokenPermissions(string inputToken)
{
string url = "https://graph.facebook.com/v2.3/debug_token?input_token=" + inputToken + "&access_token=" + getAppAccessToken();
WebRequest wrGETURL = WebRequest.Create(url);
Stream objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string jsonResponse = objReader.ReadToEnd();
JObject resonse = (JObject)JObject.Parse(jsonResponse).GetValue("data");
JToken scopes = resonse.GetValue("scopes");
List<string> returnList = new List<string>();
foreach (JToken tokrow in scopes)
{
returnList.Add((string)tokrow);
}
return returnList;
}
//DEBUG FUNCTION FOR OUTPUTTING ALL OF A TOKENS USER/PAGE PERMISSIONS
static void outputPermissions(string theToken)
{
List<string> userPermissions = getTokenPermissions(theToken);
List<string> appPermissions = getTokenPermissions(getPageToken(theToken));
Console.WriteLine("USER:");
foreach (string perm in userPermissions)
{
Console.WriteLine(perm);
}
Console.WriteLine("APP:");
foreach (string perm in appPermissions)
{
Console.WriteLine(perm);
}
Console.Read();
}
// FUNCTION THAT ACTUALLY POSTS TO THE PAGE
static async Task PostHandler(Post toPost,string theToken)
{
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "url", toPost.ImageURL },
{"access_token",getPageToken(theToken)},
{"caption",toPost.Caption}
};
Console.WriteLine("Image we are uploading is " + toPost.ImageURL);
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://graph.facebook.com/v2.3/" + PageID + "/photos", content);
Console.WriteLine("Uploaded!");
var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseString);
Console.Read();
JObject resonse = JObject.Parse(responseString);
}
}
When the post runs it returns
error #200 Requires extended permission: (manage_pages and pubish_pages) or (manage_pages and publish_actions)
The error in question was actually a bug introduced by the Facebook team that unfortunately happened to coincide with the testing of my application, since posting the bug has been logged and corrected.
More info can be found at developers.facebook.com/bugs/380833342117530
WebClient client = new WebClient();
string postData = "client_id=" + "b408123adf1e3a950876d84475587ca2"
+ "&client_secret=" + "d74a342169f5f5b369622d582f77b09e"
+ "&grant_type=password&username=" + "biksad" //your username
+ "&password=" + "369789";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://soundcloud.com/biksad/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(filePath, "#" + fileName, "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "biksad");
form.Add("track[sharing]", "public");
form.Add("oauth_token", tokenInfo);
form.Add("format", "json");
form.Add("Filename", fileName);
form.Add("Upload", "Submit Query");
string lblInfo;
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
lblInfo = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
lblInfo = ex.ToString();
}
I want to upload an audio file from my server to my soundcloud account. I got this error:
Cannot close stream until all bytes are written.
How can I detect "form" values correctly(track[title],track[sharing]...etc.)?
this link will show you what all the fields on that POST mean
http://developers.soundcloud.com/docs/api/reference#tracks
you can also use this tool they provide to look at what the URL should contain:
http://developers.soundcloud.com/console