[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.
Related
I have created an asp.net webform. One button is there on the form when I click on the button I need to redirect overpayment form authorized payment gateway with the amount and need to capture the response with the transaction id but I don't understand how to redirect over the gateway.
I read their developer document and got to know that need to pass token with URL and to generate token it needs customer profile id. so I need to understand how to generate proper token.
I am using this code to generate token:
//build a path to IframeCommunicator from the calling page
string communicatorPath = String.Format("{0}://{1}:{2}", callingPage.Scheme, callingPage.Host, callingPage.Port);
string[] segments = callingPage.Segments;
//replace the very last entry with contentx/IframeCommunicator.html
segments[segments.GetUpperBound(0)] = "/contentx/IframeCommunicator.html";
foreach(string s in segments)
communicatorPath += s;
string requestXML = String.Format("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<getHostedProfilePageRequest xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\">" +
"<merchantAuthentication>" +
"<name>{0}</name>" +
"<transactionKey>{1}</transactionKey>" +
"</merchantAuthentication>" +
"<customerProfileId>{2}</customerProfileId>" +
"<hostedProfileSettings>" +
"<setting>" +
"<settingName>hostedProfilePageBorderVisible</settingName>" +
"<settingValue>false</settingValue>" +
"</setting>" +
"<setting>" +
"<settingName>hostedProfileIFrameCommunicatorUrl</settingName>" +
"<settingValue>{3}</settingValue>" +
"</setting>" +
"</hostedProfileSettings>" +
"</getHostedProfilePageRequest>",
"API_LOGIN_ID", "TRANSACTION_KEY", CustomerProfileId, communicatorPath);
string XMLURL = "https://apitest.authorize.net/xml/v1/request.api";
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest) System.Net.HttpWebRequest.Create(XMLURL);
req.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
req.KeepAlive = false;
req.Timeout = 30000; //30 seconds
req.Method = "POST";
byte[] byte1 = null;
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte1 = encoding.GetBytes(requestXML);
req.ContentType = "text/xml";
req.ContentLength = byte1.Length;
System.IO.Stream reqStream = req.GetRequestStream();
reqStream.Write(byte1, 0, byte1.Length);
reqStream.Close();
System.Net.WebResponse resp = req.GetResponse();
System.IO.Stream read = resp.GetResponseStream();
System.IO.StreamReader io = new System.IO.StreamReader(read, new System.Text.ASCIIEncoding());
string data = io.ReadToEnd();
resp.Close();
//parse out value
XmlDocument doc = new XmlDocument();
doc.LoadXml(data);
XmlNodeList m_AccessToken = doc.GetElementsByTagName("token");
return m_AccessToken[0].InnerText;
and to generate customer profile id I am using the following code:
// set whether to use the sandbox environment, or production enviornment
ApiOperationBase < ANetApiRequest, ANetApiResponse > .RunEnvironment = AuthorizeNet.Environment.SANDBOX;
// define the merchant information (authentication / transaction id)
ApiOperationBase < ANetApiRequest, ANetApiResponse > .MerchantAuthentication = new merchantAuthenticationType() {
name = ApiLoginID,
ItemElementName = ItemChoiceType.transactionKey,
Item = ApiTransactionKey,
};
//standard api call to retrieve response
paymentType cc = new paymentType {
Item = "Credit Card"
};
paymentType echeck = new paymentType {
Item = "Credit Card"
};
List < customerPaymentProfileType > paymentProfileList = new List < customerPaymentProfileType > ();
customerPaymentProfileType ccPaymentProfile = new customerPaymentProfileType();
ccPaymentProfile.payment = cc;
customerPaymentProfileType echeckPaymentProfile = new customerPaymentProfileType();
echeckPaymentProfile.payment = echeck;
paymentProfileList.Add(ccPaymentProfile);
paymentProfileList.Add(echeckPaymentProfile);
List < customerAddressType > addressInfoList = new List < customerAddressType > ();
customerAddressType homeAddress = new customerAddressType();
homeAddress.address = "10900 NE 8th St";
homeAddress.city = "Seattle";
homeAddress.zip = "98006";
customerAddressType officeAddress = new customerAddressType();
officeAddress.address = "1200 148th AVE NE";
officeAddress.city = "NorthBend";
officeAddress.zip = "92101";
addressInfoList.Add(homeAddress);
addressInfoList.Add(officeAddress);
customerProfileType customerProfile = new customerProfileType();
// customerProfile.merchantCustomerId = "22";
customerProfile.email = emailId;
customerProfile.paymentProfiles = paymentProfileList.ToArray();
//customerProfile.shipToList = addressInfoList.ToArray();
var request = new createCustomerProfileRequest {
profile = customerProfile, validationMode = validationModeEnum.none
};
//instantiate the controller that will call the service
var controller = new createCustomerProfileController(request);
controller.Execute();
//get the response from the service (errors contained if any)
createCustomerProfileResponse response = controller.GetApiResponse();
// validate response
if (response != null) {
if (response.messages.resultCode == messageTypeEnum.Ok) {
if (response.messages.message != null) {
Console.WriteLine("Customer Profile ID: " + response.customerProfileId);
Console.WriteLine("Payment Profile ID: " + response.customerPaymentProfileIdList[0]);
Console.WriteLine("Shipping Profile ID: " + response.customerShippingAddressIdList[0]);
}
} else {
Console.WriteLine("Customer Profile Creation Failed.");
Console.WriteLine("Error Code: " + response.messages.message[0].code);
Console.WriteLine("Error message: " + response.messages.message[0].text);
}
} else {
if (controller.GetErrorResponse().messages.message.Length > 0) {
Console.WriteLine("Customer Profile Creation Failed.");
Console.WriteLine("Error Code: " + response.messages.message[0].code);
Console.WriteLine("Error message: " + response.messages.message[0].text);
} else {
Console.WriteLine("Null Response.");
}
}
return response;
but code is not working.
I am trying to fetch JSON value but failed to retrieve value and fill on DataSet and bind them on GridView and I am getting null value.
Here I have tried code please seen below:
var outputValue = cpmu.getCPMUdata(AgreementNo, AgreementedBy, YearOfAgreement);
var serializer = new JavaScriptSerializer();
dynamic obj = serializer.Deserialize<dynamic>(outputValue);
var data = obj["data"];
StringReader theReader = new StringReader(data);
DataSet theDataSet = new DataSet();
theDataSet.ReadXml(theReader);
var result = theDataSet.Tables[0];
Label3.Text = theDataSet.Tables[0].Rows[0].Field<string>("AgreementNo");
Label2.Text = theDataSet.Tables[0].Rows[0].Field<string>("Agreementby");
Label4.Text = theDataSet.Tables[0].Rows[0].Field<string>("YearofAgreement");
GridView2.DataSource = theDataSet;
GridView2.DataMember = theDataSet.Tables["Bill"].ToString();
GridView2.DataBind();
JSON code:
public string getCPMUdata(string AgreementNo, string Agreementby, string YearofAgreement)
{
//Code to accept the SSL server certificate
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
//Configuration Values
string strbaseUrl = System.Configuration.ConfigurationManager.AppSettings["baseUrl"];
string strLoginBaseUrl = System.Configuration.ConfigurationManager.AppSettings["LoginBaseUrl"];
String username = System.Configuration.ConfigurationManager.AppSettings["UserName"];
string password = System.Configuration.ConfigurationManager.AppSettings["Password"];
//***************
/* Input Values */
string strAgreementNo = AgreementNo;
string strAgreementby = Agreementby;
string strYearofAgreement = YearofAgreement;
/****************/
// Initialize the response
string returnvalue = string.Empty;
HttpWebResponse response = null;
HttpWebRequest request = null;
String responseText = null;
String authorization;
try
{
//Create the Request Url
String requestUrl = strLoginBaseUrl + "?service=" + HttpUtility.UrlEncodeUnicode(strbaseUrl + "/3DSpace/resources/CHiPSCPMSBillDetailsModeler/CHiPSCPMSBillDetails?AgreementNo=" + HttpUtility.UrlEncode(strAgreementNo) + "&Agreementby=" + HttpUtility.UrlEncode(strAgreementby) + "&YearofAgreement=" + HttpUtility.UrlEncode(strYearofAgreement));
request = WebRequest.Create(requestUrl) as HttpWebRequest;
request.Method = "GET";
request.ContentType = "application/json";
authorization = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + authorization);
response = request.GetResponse() as HttpWebResponse;
if (request.HaveResponse == true && response == null)
{
String msg = "response was not returned or is null";
throw new WebException(msg);
}
if (response.StatusCode != HttpStatusCode.OK)
{
String msg = "response with status: " + response.StatusCode + " " + response.StatusDescription;
throw new WebException(msg);
}
// get the first HTTP response content
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseText = reader.ReadToEnd();
//extract the LT code from the response string
String lt = "";
lt = responseText.Substring(responseText.LastIndexOf("\"lt\""));
lt = lt.Substring(0, lt.IndexOf(","));
lt = lt.Replace("\"lt\":", ",");
lt = lt.Replace("\"", "");
lt = lt.Replace("\"", "");
lt = lt.Replace(",", "");
//Extract Session ID from the response header
String strJsonId = "";
strJsonId = response.Headers["Set-Cookie"];
strJsonId = response.Headers["Set-Cookie"].Substring(strJsonId.LastIndexOf("JSESSIONID"));
strJsonId = strJsonId.Substring(0, strJsonId.IndexOf(";"));
strJsonId = strJsonId.Replace("JSESSIONID", "");
strJsonId = strJsonId.Replace("=", "");
strJsonId = strJsonId.Trim();
//throw exception if access token or sessionid is not available
if (lt == "" && strJsonId == "")
{
String msg = "Unable to retrieve Access Token and session Key";
throw new WebException(msg);
}
//Second HTTP Request to get the Data based on the 'lt' token, 'SessionID' and Query String parameters
WebRequest requestLast = WebRequest.Create(requestUrl);
requestLast.Headers.Add("Cookie", "JSESSIONID=" + strJsonId);
requestLast.Method = "POST";
string postData = "lt=" + lt + "&username=" + username + "&password=" + password;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
requestLast.ContentType = "application/x-www-form-urlencoded";
requestLast.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream1 = requestLast.GetRequestStream();
dataStream1.Write(byteArray, 0, byteArray.Length);
dataStream1.Close();
// Get the response.
WebResponse responseLast = requestLast.GetResponse();
dataStream1 = responseLast.GetResponseStream();
StreamReader reader1 = new StreamReader(dataStream1);
returnvalue = reader1.ReadToEnd();
// Clean up the streams.
reader.Close();
reader1.Close();
dataStream1.Close();
response.Close();
responseLast.Close();
}
catch (WebException e)
{
if (e.Response != null)
{
response = (HttpWebResponse)e.Response;
returnvalue = response.StatusCode + " " + response.StatusDescription;
}
else
{
returnvalue = e.Message;
}
}
finally
{
if (response != null)
{
response.Close();
}
}
return returnvalue;
}
public static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
Here in variable returnvalue, I get such type of error:
{"msg":"error","data":" NA
</AgreementNo> NA </Agreementby> NA
</YearofAgreement> \t\t No Data Found\t\t
</Bill>\t\t </xml>"}
I will need to send a some file to service (connect.trimble.com).
I do not understand, how upload a file to the service?
I have API instruction:
and I use this code:
string result = string.Empty;
string Url = "https://app.prod.gteam.com/tc/api/2.0/auth";
string TypeContent = "application/json";
string Method = "POST";
object obj = new
{
emailAddress = "MyMail",
key = "MyKey"
};
string Header = string.Empty;
result = RequestPost(Url, TypeContent, Method, Header, obj);
var qwe = result.Split(new char[] { '"' });
Header = "Bearer " + qwe[3];
Url = "https://app.prod.gteam.com/tc/api/2.0/files";
TypeContent = "multipart/form-data";
Method = "POST";
obj = new
{
parentId = "yVWsT_jewHs"
};
result = RequestPost(Url, TypeContent, Method, Header, obj);
private static string RequestPost(string Url, string TypeContent, string Method, string Header, object obj)
{
string result = string.Empty;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(Url);
httpWebRequest.ContentType = TypeContent;
httpWebRequest.Method = Method;
if (!string.IsNullOrEmpty(Header))
{
httpWebRequest.Headers.Add("Authorization", Header);
}
if (obj != null)
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(obj);
streamWriter.Write(json);
}
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
This code return error:
The remote server returned an error: (400) Bad Request.
I found answer myself. This topic can be closed.
string Url = "app.prod.gteam.com/tc/api/2.0/files?parentId=bHHkdeBSizA";
bHHkdeBSizA - This ID is parent folder ID, where the file will located, in current API parentId may equals rootId.
public static void UploadFile(string url, string filePath, string Header)
{
using (var client = new WebClient())
{
if (!string.IsNullOrEmpty(Header))
{
client.Headers.Add("Authorization", Header);
}
byte[] result = client.UploadFile(url, filePath);
string responseAsString = Encoding.Default.GetString(result);
}
}
I am trying to log in to a remote website via a login form so I can access a sub page via iFrame so I have to pass the validation to set a cookie or a session so I can get to the sub page with the iFrame Maybe there is a better way to do this I am not 100% sure if anyone has any suggestions please let me know. I am getting access denied error:
<script type="text/javascript">
function submitEstimoteLogin() {
setTimeout(function () {
var ifr = document.getElementById("iFrameLogin");
var ifrDoc = ifr.contentDocument || ifr.contentWindow.document;
var theForm = ifrDoc.forms[0];
var username = theform.getElementById("username");
username.value = "email";
var password = theform.getElementById("password");
password.value = "password";
var sbutton = thefrom.getElementById("");
}, 5000);
}
</script>
<iframe id="iFrameLogin" src="http://cloud.estimote.com" onload="submitEstimoteLogin();" ></iframe>
I have also tried it via code behind I am getting a 404 error:
public String GetWebContent(String username, String password)
{
String urlSignin = "https://cloud.estimote.com/";
String urlLogin = "https://cloud.estimote.com/";
Uri uriSignin = new Uri(urlSignin);
Uri uriLogin = new Uri(urlLogin);
Hashtable formData = new Hashtable();
formData.Add("username", new Hashtable());
formData.Add("password", new Hashtable());
((Hashtable)formData["username"])["value"] = username;
((Hashtable)formData["password"])["value"] = password;
String postData = "";
foreach (string name in formData.Keys)
{
postData += "&" + name + "=" + ((Hashtable)formData[name])["value"];
}
postData = postData.Substring(1);
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
HttpWebRequest webReq;
HttpWebResponse webResp;
CookieContainer cookies = new CookieContainer();
String responseString = "";
try
{
webReq = (HttpWebRequest)WebRequest.Create(urlSignin);
webResp = (HttpWebResponse)webReq.GetResponse();
for (int i = 0; i < webResp.Headers.Count; i++)
{
string name = webResp.Headers.GetKey(i);
if (name != "Set-Cookie")
continue;
string value = webResp.Headers.Get(i);
foreach (var singleCookie in value.Split(','))
{
Match match = Regex.Match(singleCookie, "(.+?)=(.+?);");
if (match.Captures.Count == 0)
continue;
webResp.Cookies.Add(
new Cookie(
match.Groups[1].ToString(),
match.Groups[2].ToString(),
"/",
webReq.Host.Split(':')[0]));
}
}
cookies.Add(webResp.Cookies);
string sessionCookie = webResp.Headers["Set-Cookie"];
responseString = new StreamReader(webResp.GetResponseStream()).ReadToEnd();
string respCookie = sessionCookie.Substring(0, sessionCookie.IndexOf(';'));
char[] separator = { '=' };
string[] cookieValues = respCookie.Split(separator);
string part1 = HttpUtility.UrlEncode(cookieValues[1]);
cookies.Add(new Cookie(cookieValues[0], part1 , "/", "cloud.estimote.com"));
webReq = (HttpWebRequest)WebRequest.Create(urlLogin);
webReq.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
webReq.Referer = urlSignin;
webReq.KeepAlive = true;
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.ContentLength = data.Length;
webReq.AllowAutoRedirect = false;
webReq.CookieContainer = cookies;
webReq.Timeout = 30000;
webReq.ReadWriteTimeout = 60000;
webReq.GetRequestStream().Write(data, 0, data.Length);
webReq.GetRequestStream().Close();
webResp = (HttpWebResponse)webReq.GetResponse();
responseString = new StreamReader(webResp.GetResponseStream()).ReadToEnd();
webResp.Close();
return responseString;
}
catch (Exception ex)
{
throw ex;
}
}
I'm trying to use the new Toggl API (v8) with .NET C#. I've based my code on the example from litemedia (http://litemedia.info/connect-to-toggl-api-with-net), but it was originally created for version 1 of the API.
private const string TogglTasksUrl = "https://www.toggl.com/api/v8/tasks.json";
private const string TogglAuthUrl = "https://www.toggl.com/api/v8/me"; //sessions.json";
private const string AuthenticationType = "Basic";
private const string ApiToken = "user token goes here";
private const string Password = "api_token";
public static void Main(string[] args)
{
CookieContainer container = new CookieContainer();
var authRequest = (HttpWebRequest)HttpWebRequest.Create(TogglAuthUrl);
authRequest.Credentials = CredentialCache.DefaultCredentials;
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded";
authRequest.CookieContainer = container;
string value = ApiToken; //= Convert.ToBase64String(Encoding.Unicode.GetBytes(ApiToken));
value = string.Format("{1}:{0}", Password, value);
//value = Convert.ToBase64String(Encoding.Unicode.GetBytes(value));
authRequest.ContentLength = value.Length;
using (StreamWriter writer = new StreamWriter(authRequest.GetRequestStream(), Encoding.ASCII))
{
writer.Write(value);
}
try
{
var authResponse = (HttpWebResponse)authRequest.GetResponse();
using (var reader = new StreamReader(authResponse.GetResponseStream(), Encoding.UTF8))
{
string content = reader.ReadToEnd();
}
HttpWebRequest tasksRequest = (HttpWebRequest)HttpWebRequest.Create(TogglTasksUrl);
tasksRequest.CookieContainer = container;
//var jsonResult = string.Empty;
var tasksResponse = (HttpWebResponse)tasksRequest.GetResponse();
MemoryStream ms = new MemoryStream();
tasksResponse.GetResponseStream().CopyTo(ms);
//using (var reader = new StreamReader(tasksResponse.GetResponseStream(), Encoding.UTF8))
//{
// jsonResult = reader.ReadToEnd();
//}
ms.Seek(0, SeekOrigin.Begin);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Task));
var tasks = ser.ReadObject(ms) as List<Task>;
ms.Close();
//var tasks = DataContractJsonConvert.DeserializeObject<Task[]>(jsonResult);
foreach (var task in tasks)
{
Console.WriteLine(
"{0} - {1}: {2} starting {3:yyyy-MM-dd HH:mm}",
task.Project.Name,
task.Description,
TimeSpan.FromSeconds(task.Duration),
task.Start);
}
}
catch (System.Exception ex)
{
throw;
}
}
The following line is returning a 404 error.
var authResponse = (HttpWebResponse)authRequest.GetResponse();
Here is code that works. Since I was looking for this answer recently there might still be others as lost as me.
Notes: I used Encoding.Default.GetBytes() because Encoding.Unicode.GetBytes() did not give me a correct result on my .NET string. I hope it doesn't depend on the default setup of Visual Studio.
The content-type is "application/json".
Sorry, I haven't tried a POST version yet.
string ApiToken = "user token goes here";
string url = "https://www.toggl.com/api/v8/me";
string userpass = ApiToken + ":api_token";
string userpassB64 = Convert.ToBase64String(Encoding.Default.GetBytes(userpass.Trim()));
string authHeader = "Basic " + userpassB64;
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(url);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "GET";
authRequest.ContentType = "application/json";
//authRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
var response = (HttpWebResponse)authRequest.GetResponse();
string result = null;
using (Stream stream = response.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
result = sr.ReadToEnd();
sr.Close();
}
if (null != result)
{
System.Diagnostics.Debug.WriteLine(result.ToString());
}
// Get the headers
object headers = response.Headers;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message + "\n" + e.ToString());
}