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
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 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();
}
I'm trying to make a request to the Square Connect api to list the payments. I'm receiving this error
"The remote server returned an error: (401) Unauthorized."
The api says
Open your favorite command-line application (such as Terminal if you're using a Mac) and run the following curl command, providing your access token where indicated:
curl -H "Authorization: Bearer PERSONAL_ACCESS_TOKEN" https://connect.squareup.com/v1/me/payments
Here is my code. What am I doing wrong?
WebRequest request = WebRequest.Create("https://connect.squareup.com/v1/me/payments");
request.ContentType = "application/json";
request.Method = "GET";
request.Headers("Authorization") = "XXXXX";
HttpWebResponse response = null;
string responseMessage = null;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK) {
using (Stream stream = response.GetResponseStream()) {
using (StreamReader reader = new StreamReader(stream)) {
responseMessage = reader.ReadToEnd();
}
}
}
Assert.IsNotNull(responseMessage);
var client = new RestSharp.RestClient();
var request = new RestRequest("https://connect.squareup.com/v1/me/payments", Method.GET);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Authorization", "Bearer xxxxx");
//setHeaders(request);
var Response = client.Execute(request);
Instead of
request.Headers("Authorization") = "XXXXX";
Do this
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + yourPersonalAccessToken);
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 want to authenticate the users who visit my website using google's OAUTH2.0.
I have successfully got the authorization_code in response and now I am facing problem when I make a 'POST request' to Google when getting an access token. The problem is that the request is being continued over the time and I'm not getting any response.
Is there anything wrong in the code I have written below?
StringBuilder postData = new StringBuilder();
postData.Append("code=" + Request.QueryString["code"]);
postData.Append("&client_id=123029216828.apps.googleusercontent.com");
postData.Append("&client_secret=zd5dYB9MXO4C5vgBOYRC89K4");
postData.Append("&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=124545459218.apps.googleusercontent.com&client_secret={zfsgdYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string addons = "/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=123029216828.apps.googleusercontent.com&client_secret={zd5dYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code";
request.ContentLength = addons.Length;
Stream str = request.GetResponse().GetResponseStream();
StreamReader r = new StreamReader(str);
string a = r.ReadToEnd();
str.Close();
r.Close();
As I mentioned in my comment, you just have a few minor mistakes in your code. As it stands, you're not actually POST-ing anything. I'm assuming you intend to send the postData string.
The following should work:
//Build up your post string
StringBuilder postData = new StringBuilder();
postData.Append("code=" + Request.QueryString["code"]);
postData.Append("&client_id=123029216828.apps.googleusercontent.com");
postData.Append("&client_secret=zd5dYB9MXO4C5vgBOYRC89K4");
postData.Append("&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
//Create a POST WebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=124545459218.apps.googleusercontent.com&client_secret={zfsgdYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//Write your post string to the body of the POST WebRequest
var sw = new StreamWriter(request.GetRequestStream());
sw.Write(postData.ToString());
sw.Close();
//Get the response and read it
var response = request.GetResponse();
var raw_result_as_string = (new StreamReader(response.GetResponseStream())).ReadToEnd();
You were just missing the part where you attached the string to your POST WebRequest.