I'm working on Salesforce and wanting to get cases fields in it. found the command
curl https://yoursite.desk.com/api/v2/cases \
-u email:password \
-H 'Accept: application/json'
And I tried it in command prompt as
curl https://xxx.desk.com/api/v2/cases \-u abc#gmail.com:xxxxxxxxx \ -H 'Accept: application/json'
I have tried the below code in C#
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://xxxx.desk.com/api/v2/cases");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "text/xml";
httpWebRequest.Method = "GET";
httpWebRequest.Credentials = new NetworkCredential("username", "password");
var response = httpWebRequest.GetResponse();
But it is returning an error
The remote server returned an error: (401) Unauthorized.
CURL is just a client for WebRequests
the default C# option is
WebRequest Class
you can also use Restsharp
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://xxxx.desk.com/api/v2/cases");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "text/xml";
httpWebRequest.Method = "GET";
httpWebRequest.Credentials = new NetworkCredential("username", "password");
httpWebRequest.Headers.Add("Authorization", "Basic reallylongstring");
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string text;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string fddf = streamReader.ReadToEnd();
}
Related
I am attempting to make a POST request to a server. The following works when I CURL using git Bash:
curl -X POST -H "Content-Type: application/octet-stream" -H "User-Agent: MyUserAgent" --data-binary #MyDocument.xlsx http://myUrl.com
I know I can make POST requests using json as follows (in C#):
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myUrl);
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "application/json";
request.UserAgent = myUserAgent;
using (var stream = await request.GetRequestStreamAsync())
{
using (StreamWriter streamWriter = new StreamWriter(stream))
{
streamWriter.Write(myJsonData);
}
}
using (HttpWebResponse webResponse = (HttpWebResponse) await request.GetResponseAsync())
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
string response = reader.ReadToEnd();
//do stuff with response
}
}
My difficulty is basically combining the two. I know I need to change the request.ContentType to "application/octet-stream", but that is not enough. How do I incorporate the "--data-binary #MyDocument.xlsx" in the HttpWebRequest?
Anyone have any ideas? Thanks!
I suggest you look into WebClient since it's easier to implement:
WebClient client = new WebClient();
byte[] response = client.UploadFile(myUrl,fileName);
I´m trying to write this call
curl -d #credentials.json -H "Content-Type: application/json" http://128.136.179.2:5000/v2.0/tokens
using WebRequest.
I´m not sure about how should I indicate the credentials:
{"auth":{"passwordCredentials":{"username": "user", "password": "pass"},"tenantName": "tenant"}}
Right now, I´m doing this:
WebRequest request = WebRequest.Create(serverUrl + "tokens");
request.ContentType = "application/json";
request.Method = "GET";
string authInfo = "passwordCredentials:{username:" + username + ", password:" + password + "},tenantName:" + tenantname;
request.Headers["Authorization"] = "Basic " + authInfo;
WebResponse response = request.GetResponse();
Thanks!
Your curl just sends data to that host. It doesn't add it to header. Same thing you shoud do in c#
var request = WebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "POST"; // I assume your token server accept post request for tokens? It not change for right verb.
new StreamWriter(request.GetRequestStream()).Write(jsondata);// just for demo. you should also close writer.
request.ContentLength = jsondata.Length;
var response = request.GetResponse();
For more information how to use request you can look at msdn
https://msdn.microsoft.com/en-us/library/debx8sh9(v=vs.110).aspx
trying to convert cURL to C#
curl -v -X POST -d '{"signature":"2d0c311eb0fe9cd84fcd1b875759c313","marker":"PutYourMarkerHere","host":"beta.aviasales.ru","user_ip":"127.0.0.1","locale":"ru","trip_class":"Y","passengers":{"adults":1,"children":0,"infants":0},"segments":[{"origin":"MOW","destination":"LED","date":"2015-05-25"},{"origin":"LED","destination":"MOW","date":"2015-06-18"}]}' -H 'Content-type:application/json' http://api.travelpayouts.com/v1/flight_search
this is my code, what is wrong with it? i'm getting 500 internal server error
var data = "{'signature':'2d0c311eb0fe9cd84fcd1b875759c313','marker':'72872','host':'mysite.com','user_ip':'112.199.36.67','locale':'ru','trip_class':'Y','passengers':{'adults':1,'children':0,'infants':0},'segments':[{'origin':'MOW','destination':'LED','date':'2015-05-25'},{'origin':'LED','destination':'MOW','date':'2015-06-18'}]}";
var request = (HttpWebRequest)WebRequest.Create(new Uri("http://api.travelpayouts.com/v1/flight_search"));
request.Method = "POST";
request.AllowAutoRedirect = false;
request.Accept = "*/*";
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (var reqStream = request.GetRequestStream())
using (var writer = new StreamWriter(reqStream))
{
writer.Write(data);
}
var response = request.GetResponse();
MessageBox.Show(response.Headers.ToString());
I am banging my head against a wall trying to convert a working curl command to a c# WebRequest.
I have read through quite a few postings and I was pretty sure I had the code right but it still will not work.
Can anyone see what I am doing wrong please?
Here is the working curl command:
curl -k -u x:reallylongstring -H "Content-Type: application/json" https://api.somewhere.com/desk/external_api/v1/customers.json
And this is the code I have written in c#:
WebRequest wrGETURL;
wrGETURL = WebRequest.Create("https://api.somewhere.com/desk/external_api/v1/customers.json");
wrGETURL.Method = "GET";
wrGETURL.ContentType = "application/json";
wrGETURL.Credentials = new NetworkCredential("x", "reallylongstring");
Stream objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string responseFromServer = objReader.ReadToEnd();
But the api responds:
The remote server returned an error: (406) Not Acceptable.
Any help would be much appreciated!
Thanks
Based on Nikolaos's pointers I appear to have fixed this with the following code:
public static gta_allCustomersResponse gta_AllCustomers()
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.somewhere.com/desk/external_api/v1/customers.json");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "*/*";
httpWebRequest.Method = "GET";
httpWebRequest.Headers.Add("Authorization", "Basic reallylongstring");
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
gta_allCustomersResponse answer = JsonConvert.DeserializeObject<gta_allCustomersResponse>(streamReader.ReadToEnd());
return answer;
}
}
Here is my solution to post json data to using an API call or webservice
public static void PostJsonDataToApi(string jsonData)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.somewhere.com/v2/cases");
httpWebRequest.ReadWriteTimeout = 100000; //this can cause issues which is why we are manually setting this
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "*/*";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", "Basic ThisShouldbeBase64String"); // "Basic 4dfsdfsfs4sf5ssfsdfs=="
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
// we want to remove new line characters otherwise it will return an error
jsonData= thePostBody.Replace("\n", "");
jsonData= thePostBody.Replace("\r", "");
streamWriter.Write(jsonData);
streamWriter.Flush();
streamWriter.Close();
}
try
{
HttpWebResponse resp = (HttpWebResponse)httpWebRequest.GetResponse();
string respStr = new StreamReader(resp.GetResponseStream()).ReadToEnd();
Console.WriteLine("Response : " + respStr); // if you want see the output
}
catch(Exception ex)
{
//process exception here
}
}
This is the curl command I use to post json data:
curl http://IP:PORT/my/path/to/endpoint -H 'Content-type:application/json' -d '[{...json data...}]'
This is equivalent to the above curl command with C#:
var url = "http://IP:PORT/my/path/to/endpoint";
var jsonData = "[{...json data...}]";
using (var client = new WebClient())
{
client.Headers.Add("content-type", "application/json");
var response = client.UploadString(url, jsonData);
}
According to this question regarding 406: What is "406-Not Acceptable Response" in HTTP? perhaps you could try adding an Accept header to your request? Maybe curl adds that automatically.
Also there's a -k in your curl request telling it to ignore SSL validation, which I'm not sure if it affects the .NET code. In other words, does curl still work without the '-k'? Then, no worries. Otherwise, perhaps you need to tell .NET to also ignore SSL validation.
I'm trying to send a test notification to my ipod via UrbanAirship with C#. I've tried many code snippets trying to send my notification to UrbanAirship from my Windows server, yet I always end up with a 401 error.
Here's my latest code:
string postData = "{\"aps\": {\"badge\": 1, \"alert\": \"Hello from Urban Airship!\"}, \"device_tokens\": [\""+ devToken +"\"]}";
var uri = new Uri("https://go.urbanairship.com/api/push/");
var encoding = new UTF8Encoding();
var request = (HttpWebRequest)WebRequest.Create(uri);
char[] charArray = Encoding.UTF8.GetChars(Encoding.UTF8.GetBytes(postData));
request.Method = "POST";
request.Credentials = new NetworkCredential(username, password);
request.ContentType = "application/json";
request.ContentLength = encoding.GetByteCount(charArray);
using (var stream = request.GetRequestStream())
{
stream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
stream.Close();
var response = request.GetResponse();
response.Close();
}
Note: I've verified that my username and password are correct.
===UPDATE===
I would say that there's something woring with my urbanairship config or so but the following worked:
curl -X PUT -u "appKey:appSecret" -H "Content-Type: application/json" --data '{"alias": "myalias"}' https://go.urbanairship.com/api/device_tokens/myTOken/
Fixed, I've modified my code and most important: YOUR PASSWORD IS THE APPLICATION MASTER SECRET
string postData = "{\"aps\": {\"badge\": 1, \"alert\": \"Hello from Urban Airship!\"}, \"device_tokens\": [\""+ devToken +"\"]}";
var uri = new Uri("https://go.urbanairship.com/api/push/");
var encoding = new UTF8Encoding();
var request = (HttpWebRequest)WebRequest.Create(uri);
char[] charArray = Encoding.UTF8.GetChars(Encoding.UTF8.GetBytes(postData));
request.Method = "POST";
request.Credentials = new NetworkCredential(username, password);
request.ContentType = "application/json";
request.ContentLength = encoding.GetByteCount(charArray);
using (var stream = request.GetRequestStream())
{
stream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
stream.Close();
var response = request.GetResponse();
response.Close();
}