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);
}
}
Related
In trello api documentation we have this POST method to upload a file into a card but using curl.
curl -v -F token={TrelloToken} -F file=#test.pdf https://api.trello.com/1/cards/5bbce18fa4a337483b145a57/attachments\?key\={APIKey}\&token\={TrelloToken}
As I am using C#, I did build this method to try to upload an image but it turns out that the file upload (or not) but it seems that the extention of the file is not the correct one. I actually don't know if it is the file that I request to upload or not, because I am not able to open when I download it. The attached image shown the result of a test that I made. In this link have the documentation and I don't know where I am stuck.
public static string CreateCard(string title, string description, string listId, string imagePath, string key, string token)
{
string id = string.Empty;
string url = "https://api.trello.com/1/cards";
Cards card = new Cards();
card.name = title;
card.desc = description;
card.idList = listId;
card.pos = "bottom";
card.key = key;
card.token = token;
card.keepFromSource = "all";
string jsonData = JsonConvert.SerializeObject(card);
string serverResponse = GenericPost(url, jsonData, token, key);
var objId = JObject.Parse(serverResponse)["id"];
id = objId.ToString();
UploadAttachment(key, token, id, imagePath,title);
return id;
}
public static void UploadAttachment(string key, string token, string cardId, string imagePath,string name)
{
System.Windows.Forms.MessageBox.Show(imagePath);
string url = $"https://api.trello.com/1/cards/{cardId}/attachments";
Attachments at = new Attachments();
at.token = token;
at.key = key;
at.id = cardId;
at.file = imagePath;
at.mimeType = "image/jpeg";
at.name = name;
string json = JsonConvert.SerializeObject(at);
string respo= GenericPostImage(url,json,token,key);
}
public static string GenericPostImage(string url, string JSONpostData, string token, string key)
{
var request = (HttpWebRequest)WebRequest.Create(url);
string header = $"key={key}&token={token}";
request.Headers.Add(HttpRequestHeader.Authorization, header);
request.Method = "POST";
request.ContentType = "application/json";
using (StreamWriter wtr = new StreamWriter(request.GetRequestStream()))
{
wtr.Write(JSONpostData);
wtr.Close();
}
HttpWebResponse response = null;
string strResponseValue = string.Empty;
try
{
response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
strResponseValue = reader.ReadToEnd();
}
}
}
}
catch
{
System.Windows.Forms.MessageBox.Show("Error");
}
return strResponseValue;
}
I am trying to return the response of productRating in this HTTP call. I have tried several ways but haven't been successful. Any idea? The response is a json with an object that I want to get access to the streamInfo>avgRatings>_overall
public double GetRatings(string productId)
{
const string URL = "https://comments.au1.gigya.com/comments.getStreamInfo";
var apiKey = "3_rktwTlLYzPlqkzS62-OxNjRDx8jYs-kV40k822YlHfEx5VCu93fpUo8JtaKDm_i-";
var categoryId = "product-ratings";
var urlParams = "?apiKey=" + apiKey + "&categoryID=" + categoryId + "&streamID=" + productId + "";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = JsonConvert.DeserializeObject(client.GetAsync(urlParams).Result.Content.ReadAsStringAsync().Result);
var productrating = (response["streamInfo"]["avgRatings"]["_overall"]);
return;
}
GetRatings Erroe: not all code paths return a value.
Productrating Error:can not apply indexing with [] to an expression of type HttpResponseMessage
return Error: an object of a type convertable to double is required
ApiCall has to return something. Looking at the example below.
#functions {
public static string ApiCall()
{
return "Hello World!";
}
}
#{
var ratings = ApiCall();
}
#if (ratings != null)
{
<div class="gig-rating-stars" content=#ratings></div>
}
I am using this function for POST API Call and it returns response string and if you want to add security features you can send it in JObject because its the secure channel to send Jobject as a parameter on URL
## Code Start ##
protected string RemoteApiCallPOST(JObject elements, string url)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
// JObject jsonResult = new JObject();
string id;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(elements);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
id = (streamReader.ReadToEnd()).ToString();
return id;
}
}
catch (Exception EX)
{
return "";
}
}
Code End
The only change I needed to do is changing "var" to "dynamic" in :
dynamic response = JsonConvert.DeserializeObject(client.GetAsync(urlParams).Result.Content.ReadAsStringAsync().Result);
I have an OpenIdConnect Server I'm connecting to an I would like to forward token data the first time logging in to be stored on the server. Currently I'm doing this to forward the access token
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function () {
log(xhr.status, JSON.parse(xhr.responseText));
}
xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);
xhr.send();
I want to send the Profile Data as well but I don't know the proper header.
How can I do something like this:
xhr.setRequestHeader("Authorization-Profile", "Bearer " + user.profile);
Does anyone know the proper header so I can add these claims to the access token.
Here is an example of what we did in one of our project:
Created a common API response class as below:
public class ApiCommonResponse
{
public object Object { get; set; }
public int httpStatus { get; set; }
public string httpErrorMessage { get; set; }
}
And a generic method to call GET and POST API endpoints. This method will map the response to the supplied data model and will return you the object.
public static ApiCommonResponse GetApiData<T>(string token, T dataModel, string apiEndPoint = null)
{
var responseText = "";
var apiCommonResponse = new ApiCommonResponse();
if (apiEndPoint != null)
{
var request = (HttpWebRequest)WebRequest.Create(apiEndPoint);
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + token);
request.Headers.Add("X-Api-Version", "");
try
{
var httpResponse = (HttpWebResponse)request.GetResponse();
var stream = httpResponse.GetResponseStream();
if (stream != null)
{
using (var streamReader = new StreamReader(stream))
{
responseText = streamReader.ReadToEnd();
}
}
}
catch (WebException we)
{
var stream = we.Response.GetResponseStream();
if (stream != null)
{
var resp = new StreamReader(stream).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(resp);
throw new Exception(obj.ToString());
}
}
}
var jsonSettings = new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Ignore };
apiCommonResponse.Object = JsonConvert.DeserializeObject<T>(responseText, jsonSettings);
apiCommonResponse.httpStatus = 0;
return apiCommonResponse;
}
public static ApiCommonResponse PostApiData<T>(string username, string token, T dataModel, string apiEndPoint = null)
{
var apiCommonResponse = new ApiCommonResponse();
if (apiEndPoint == null) return null;
var webRequest = WebRequest.Create(apiEndPoint);
webRequest.Method = "POST";
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + token);
webRequest.Headers.Add("X-Api-Version", "");
using (var requeststreams = webRequest.GetRequestStream())
{
using (var sw = new StreamWriter(requeststreams))
{
sw.Write(JsonConvert.SerializeObject(dataModel));
}
}
try
{
var httpStatus = (((HttpWebResponse)webRequest.GetResponse()).StatusCode);
var httpMessage = (((HttpWebResponse)webRequest.GetResponse()).StatusDescription);
using (var s = webRequest.GetResponse().GetResponseStream())
{
if (s == null) return null;
using (var sr = new StreamReader(s))
{
var responseObj = sr.ReadToEnd();
if (!string.IsNullOrEmpty(responseObj))
{
apiCommonResponse = JsonConvert.DeserializeObject<ApiCommonResponse>(responseObj);
}
}
apiCommonResponse.httpStatus = (int)httpStatus;
apiCommonResponse.httpErrorMessage = httpMessage;
apiCommonResponse.Object = apiCommonResponse.Object;
}
}
catch (WebException we)
{
var stream = we.Response.GetResponseStream();
if (stream != null)
{
var resp = new StreamReader(stream).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(resp);
throw new Exception(obj.ToString());
}
}
return apiCommonResponse;
}
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());
}
I have searched everywhere and have not found an answer to my question. Let me get straight to the point. I have developed an android messaging app for the purpose of experimenting with C2DM. My app get's the registration ID and it gets displayed in my Log correctly. I then send that key through to my C# web service.
The C# Web service then applies for an auth token, which works fine. No problem so far. But, as soon as I POST my body items (registration_id, collapse_key, data.<key>, delay_while_idle) with my header(GoogleLogin auth=[AUTH_TOKEN]) I get the response: "Error=InvalidRegistration".
There is no reason for this not to work. And yes, I have tried every solution available here in stack overflow, but remained unsuccessful. Here is my main code for my server side:
WebRequest theRequest;
HttpWebResponse theResponse;
ArrayList theQueryData;
theRequest = WebRequest.Create("https://www.google.com/accounts/ClientLogin");
theRequest.Method = "POST";
theQueryData = new ArrayList();
String [] test = new String[5];
test[0] = "accountType=HOSTED_OR_GOOGLE";
test[1] = "Email=XXXXXXXXXXXXXXXXX";
test[2] = "Passwd=XXXXXXXXXXXXXXXX";
test[3] = "Source=Domokun";
test[4] = "service=ac2dm";
// Set the encoding type
theRequest.ContentType = "application/x-www-form-urlencoded";
// Build a string containing all the parameters
string Parameters = String.Join("&", (String[])test);
theRequest.ContentLength = Parameters.Length;
// We write the parameters into the request
StreamWriter sw = new StreamWriter(theRequest.GetRequestStream());
sw.Write(Parameters);
sw.Close();
// Execute the query
theResponse = (HttpWebResponse)theRequest.GetResponse();
StreamReader sr = new StreamReader(theResponse.GetResponseStream());
String value = sr.ReadToEnd();
String token = ParseForAuthTokenKey(value);
String value2 = "";
if (value != null)
{
WebRequest theRequest2;
HttpWebResponse theResponse2;
ArrayList theQueryData2;
theRequest2 = WebRequest.Create("http://android.clients.google.com/c2dm/send");
theRequest2.Method = "POST";
theQueryData2 = new ArrayList();
String[] test2 = new String[4];
test[0] = "registration_id=" + registerid;
test[1] = "collapse_key=0";
test[2] = "data.payload=Jannik was hier";
test[3] = "delay_while_idle=0";
// Set the encoding type
theRequest2.ContentType = "application/x-www-form-urlencoded";
// Build a string containing all the parameters
string Parameters2 = String.Join("&", (String[])test2);
theRequest2.ContentLength = Parameters2.Length;
theRequest2.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + token);
// We write the parameters into the request
StreamWriter sw2 = new StreamWriter(theRequest2.GetRequestStream());
sw2.Write(Parameters2);
sw2.Close();
// Execute the query
theResponse2 = (HttpWebResponse)theRequest2.GetResponse();
StreamReader sr2= new StreamReader(theResponse2.GetResponseStream());
value2 = sr2.ReadToEnd();
public static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
private static string ParseForAuthTokenKey(string webResponse)
{
string tokenKey = String.Empty;
if (webResponse.Contains(AuthTokenHeader))
{
tokenKey = webResponse.Substring(webResponse.IndexOf(AuthTokenHeader) + AuthTokenHeader.Length);
if (tokenKey.Contains(Environment.NewLine))
{
tokenKey.Substring(0, tokenKey.IndexOf(Environment.NewLine));
}
}
return tokenKey.Trim();
}
All I can think is that my C2DM account isn't registered correctly. Could this be it? Or are there an error in my code that I'm missing?
OK. I've found the solution.
string requestBody = string.Format("registration_id={0}&collapse_key{1}&data.key=value",
HttpUtility.UrlEncode(registrationId), "collapse");
string responseBody = null;
WebHeaderCollection requestHeaders = new WebHeaderCollection();
WebHeaderCollection responseHeaders = null;
requestHeaders.Add(HttpRequestHeader.Authorization, string.Format("GoogleLogin auth={0}", authToken));
httpClient.DoPostWithHeaders(c2dmPushUrl,
requestBody,
"application/x-www-form-urlencoded",
out responseBody,
out responseHeaders,
requestHeaders);
public bool DoPostWithHeaders(string url,
string requestBody,
string contextType,
out string responseBody,
out WebHeaderCollection responseHeaders,
WebHeaderCollection requestHeaders = null)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// FIRST SET REQUEST HEADERS
httpWebRequest.Headers = requestHeaders;
httpWebRequest.Method = "POST";
// THEN SET CONTENT TYPE - THE ORDER IS IMPORTANT
httpWebRequest.ContentType = contextType;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(requestBody);
httpWebRequest.ContentLength = data.Length;
stream = httpWebRequest.GetRequestStream();
stream.Write(data, 0, data.Length);
....
....
....
}