Just need some help to send a POST in C# that has the same data as the following curl
curl -v -u {email_address}:{password} https://{subdomain}.zendesk.com/api/v2/users.json \
-H "Content-Type: application/json" -X POST -d '{"user": {"name": "Roger Wilco", "email": "roge#example.org"}}'
I have the basic stuff below just need to change a bit not sure how... the issue is I am no sure how to create a json of {"user": {"name": "Roger Wilco", "email": "roge#example.org"}}
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://home67.zendesk.com/api/v2/users.json");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
User user = new User();
user.email = this.email;
user.name = this.name;
string json = new JavaScriptSerializer().Serialize(user);
WriteObject(json.ToString());
// the above currently only gives {"name":"something", "email":"something#something"}
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
WriteObject(result);
}
The simplest way is probably to serialize an anonymous type with a user property:
string json = new JavaScriptSerializer().Serialize(new { user = user });
// {"user":{"name":"Roger Wilco","email":"roger#example.org"}}
Related
When I try to upload a file to an API with the help of RestSharp, I get the response:
'Error calling UploadFile: {"message":"The given data was invalid.","errors":{"file":["The file field is required."]}}'
When I upload the file to the API using their plattform everything works as expected.
Request:
curl -X POST "https://{URL}/v1/customer/files/ef02f89c-accf-4ca5-a05a-456cf65242d3" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "file=#dancing-penguins.gif;type=image/gif"
Response:
Code 200
Response body
Download
{
"id": "ef02f89c-accf-4ca5-a05a-456cf65242d3",
"fileName": "dancing-penguins.gif"
}
My code to upload the file:
private ApiResponse<File> UploadFileWithHttpInfo(File file, byte[] fileData)
{
var pathParams = new Dictionary<string, string>() { ["id"] = Configuration.ApiClient.ParameterToString(file.Id) };
var headerParams = new Dictionary<string, string>(Configuration.DefaultHeader);
string httpHeaderAccept = "application/json";
if (httpHeaderAccept != null)
headerParams.Add("Accept", httpHeaderAccept);
if (!string.IsNullOrEmpty(Configuration.AuthString))
headerParams["Authorization"] = Configuration.AuthString;
var fileParams = new Dictionary<string, FileParameter> { ["file"] = FileParameter.Create(file.FileName, fileData, file.FileName, MapContentTypeFromExtension(file.FileName)) };
string path = "/v1/customer/files/{id}";
Method method = Method.POST;
var request = new RestRequest(path, method);
foreach (var param in pathParams) request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment);
foreach (var param in headerParams) request.AddHeader(param.Key, param.Value);
foreach (var param in fileParams) request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentLength, param.Value.ContentType);
// set user agent
//RestClient.UserAgent = Configuration.UserAgent;
request.RequestFormat = DataFormat.Json;
InterceptRequest(request);
var response = RestClient.Execute(request);
InterceptResponse(request, response);
Exception exception = ExceptionFactory(nameof(UploadFile), response);
return exception == null ? new ApiResponse<File>(Configuration, response) : throw exception;
}
Any help is appreciated.
I passed the wrong argument to the RestSharps AddFile method. Instead of the tag: 'file', I passed the filename.
foreach (var param in fileParams) request.AddFile("file", param.Value.Writer, param.Value.FileName, param.Value.ContentLength, param.Value.ContentType);
I'm working on a web app that will manage WooCommerce orders, over WooCommerce REST API.
I'm trying to update the order status after the user clicks a button.
When I run the app, click the button, I get a 200 - OK status, but the order remains the same, no update is done.
This is the cURL example on the documentation:
curl -X PUT https://example.com/wp-json/wc/v3/orders/727 \
-u consumer_key:consumer_secret \
-H "Content-Type: application/json" \
-d '{
"status": "completed"
}'
On Postman, i execute the query and it works just fine, adding this code on the body (raw-JSON), over a PUT request:
{
"status": "cancelled"
}
Now, this is my C# code, on the onClick action of the button:
#region Request
string nuevoEstado = "trash";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlRequestInicial);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "PUT";
httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(apiUsr + ":" + apiPwd));
httpWebRequest.UseDefaultCredentials = true;
httpWebRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
var serializaer = new JavaScriptSerializer();
var elJeison = serializaer.Serialize(new
{
status = nuevoEstado
});
streamWriter.Write(elJeison);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string returnString = httpResponse.StatusCode.ToString();
ltErr.Text = returnString;
#endregion
returnString shows "OK", but no update is done.
Any help is muchly appreciated
Solved it with another approach. I post it here in case anyone gets to the same issue I had:
I changed the method to a async void
using System.Net.Http;
using System.Net.Http.Headers;
protected async void btnCompletarPedidoApiAxnAsync (object sender, EventArgs e)
{
...
}
And I set a using block, changing the approach over a HttpClient();
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("PUT"), laUrl))
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes(apiUsr + ":" + apiPwd));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
request.Content = new StringContent("{\n \"status\": \"completed\"\n}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await httpClient.SendAsync(request);
string responseBody = await response.Content.ReadAsStringAsync();
}
}
I am getting 401 access error when running the below code. Can someone please tell me what I am doing wrong. thanks
The Curl provided is: curl -X GET --header "Authorization: " --header "Authorization: Bearer kgffj*dfkgj40fdgjkjkdfjUHHHDNhdfj" "https://api.united.com/v1/accounts"
string url = "https://api.united.com/v1/accounts";
WebRequest myReq = WebRequest.Create(url);
string credentials = "kgffj*dfkgj40fdgjkjkdfjUHHHDNhdfj";
CredentialCache mycache = new CredentialCache();
myReq.Headers["Authorization"] = "Bearer " + Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Console.WriteLine(content);
var json = "[" + content + "]"; // change this to array
var objects = JArray.Parse(json); // parse as array
foreach (JObject o in objects.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = p.Value.ToString();
Console.Write(name + ": " + value);
}
}
Console.ReadLine();
The curl request would be represented like this in C#
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.united.com/v1/accounts"))
{
request.Headers.TryAddWithoutValidation("Authorization", "Bearer kgffj*dfkgj40fdgjkjkdfjUHHHDNhdfj");
var response = await httpClient.SendAsync(request);
}
}
I could not test this code as the url https://api.united.com/v1/accounts times out from my system. But This should work.
As others have pointed out you should not need to convert the token to base 64 as its not converted to base64 in the curl
I am assuming that you want to perform the same request that you would run if you use the curl command in your question
The code provided above fixes the http request.
The response object in the above code is of Type HttpResponseMessage
This object has a HttpResponseMessage.Content Property on it
This Content is of type HttpContent and it has a public method ReadAsStringAsync() which will
Serialize the HTTP content to a string as an asynchronous operation.
and that is your JSON content that you are looking for.
So your code should look like this
public static async Task<string> GetData()
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.united.com/v1/accounts"))
{
request.Headers.TryAddWithoutValidation("Authorization", "Bearer kgffj*dfkgj40fdgjkjkdfjUHHHDNhdfj");
var response = await httpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
}
This method is an async method,Since the code you provided in the question is not async you would need to use
string json = GetData().Result;
if you want to use it in a non async function
or if you change your method calling this method to async then you can use the await keyword like this
string json = await GetData();
It is unlikely you can just hardcode an OAuth Bearer token. You need to lookup the details for authentication for that specific API to see how to obtain a Bearer token for use in the API.
I am currently trying to send POST request in C# (API), but I have some troubles with Content Type and Authorization, because its in format apiHash, apiKey.
Curl example:
curl -i -XPOST https://sandboxapi.g2a.com/v1/order \
-H "Authorization: qdaiciDiyMaTjxMt, 74026b3dc2c6db6a30a73e71cdb138b1e1b5eb7a97ced46689e2d28db1050875" \
-H 'Content-Type: application/json' \
-d '{"product_id": "10000027819004", "max_price": 45.0}'
Documentation for API:
https://www.g2a.com/integration-api/documentation/#api-Orders-AddOrder
And this is my code so far:
private static readonly HttpClient client = new HttpClient();
public async Task < string > makeRequest() {
var values = new Dictionary < string,
string > {
{
"product_id",
"10000027819004"
},
{
"max_price",
"45.0"
}
};
var content = new FormUrlEncodedContent(values);
AuthenticationHeaderValue authHeaders = new AuthenticationHeaderValue("qdaiciDiyMaTjxMt", "74026b3dc2c6db6a30a73e71cdb138b1e1b5eb7a97ced46689e2d28db1050875");
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
client.DefaultRequestHeaders.Authorization = authHeaders;
var response = await client.PostAsync("https://sandboxapi.g2a.com/v1/order", content);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
I tried multiple solutions, but I seem to be unable to have it all correct together(Content-Type, Authorization and parameters).
You must set the content type like this :
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
This will solve the issue.
You are sending FormUrlEncodedContent which is not JSON while the curl example is sending JSON.
Refactor your method to use actual serialized JSON string in a StringContent with proper content type set.
public async Task<string> makeRequest() {
var values = new {
product_id = "10000027819004",
max_price = 45.0
};
//-d '{"product_id": "10000027819004", "max_price": 45.0}'
var json = JsonConvert.SerializeObject(values); //using Json.Net
var content = new StringContent(json);
var auth = "qdaiciDiyMaTjxMt, 74026b3dc2c6db6a30a73e71cdb138b1e1b5eb7a97ced46689e2d28db1050875";
//-H "Authorization: qdaiciDiyMaTjxMt, 74026b3dc2c6db6a30a73e71cdb138b1e1b5eb7a97ced46689e2d28db1050875" \
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", auth);
//-H 'Content-Type: application/json' \
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
var response = await client.PostAsync("https://sandboxapi.g2a.com/v1/order", content);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
I'm trying to convert curl request to WebRequest in C# but not able to get the response as it always returns 401 unauthorized error
Here is the working curl request:
curl -k -v https://api.demo.peertransfer.com/v1/transfers -H "Content-Type: application/json" -X POST -d "{\"provider\":\"HUL\",\"payment_destination\":\"hult-applicationfee\",\"amount\":\"29000\",\"callback_url\":\"http://studentapplication.local/en/nextsteps\",\"callback_id\":\"abc1234546asas\",\"dynamic_fields\":{\"student_id\":\"32453245\",\"student_first_name\":\"Candy\",\"student_last_name\":\"Student\"}}" -H "X-Peertransfer-Digest: zYUt+Pn0A06wsSbCrrbAZn68Aslq9CbSUAKBrUEwIzI="
Output:
The result in the red box is what I need to get in WebRequest Response,
here is my C# code
private void testnewfunc()
{
string value = "{\"provider\":\"HUL\",\"payment_destination\":\"hult-applicationfee\",\"amount\":\"29000\",\"callback_url\":\"http://studentapplication.local/en/nextsteps\",\"callback_id\":\"abc1234546asas\",\"dynamic_fields\":{\"student_id\":\"32453245\",\"student_first_name\":\"Candy\",\"student_last_name\":\"Student\"}}";
var URI = new Uri("https://api.demo.peertransfer.com/v1/transfers");
byte[] data = System.Text.ASCIIEncoding.Default.GetBytes(value);
var requst = (HttpWebRequest)WebRequest.Create(URI);
requst.UserAgent = "curl/7.43.0";
requst.Method = "POST";
requst.KeepAlive = true;
requst.AllowAutoRedirect = true;
requst.ContentType = " application/json";
requst.ContentLength = data.Length;
// wc.Headers["Content-Type"] = "application/json";
requst.Accept = "*/*";
//Or any other encoding type.
string result = System.Convert.ToBase64String(data);
var uname = "hultdemo2015";
var pword = "gEejgC0GF8pCbI7C";
var creds = string.Format("{0}:{1}", uname, pword);
creds = Convert.ToBase64String(Encoding.ASCII.GetBytes(creds));
requst.Headers["Authorization"] = string.Format("{0} {1}", "Basic", creds);
requst.Headers["X-Peertransfer-Digest"] = string.Format("{0}", "zYUt+Pn0A06wsSbCrrbAZn68Aslq9CbSUAKBrUEwIzI=");
using (Stream stream = requst.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var httpResponse = (HttpWebResponse)requst.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
// return true;
}
}
Not sure what I'm making wrong in the WebRequest.
Here's my solution:
var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
var message = new HttpRequestMessage(HttpMethod.Post, new Uri("https://api.demo.peertransfer.com/v1/transfers"));
message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
message.Headers.Add("X-Peertransfer-Digest", "zYUt+Pn0A06wsSbCrrbAZn68Aslq9CbSUAKBrUEwIzI=");
message.Content = new StringContent("{\"provider\":\"HUL\",\"payment_destination\":\"hult-applicationfee\",\"amount\":\"29000\",\"callback_url\":\"http://studentapplication.local/en/nextsteps\",\"callback_id\":\"abc1234546asas\",\"dynamic_fields\":{\"student_id\":\"32453245\",\"student_first_name\":\"Candy\",\"student_last_name\":\"Student\"}}", Encoding.UTF8, "application/json");
var responseMessage = await client.SendAsync(message);
MessageBox.Show(string.Format("Status Code: {0}{1}Content-Type: {2}{1}Date: {3}{1}Location:{4}", responseMessage.StatusCode, Environment.NewLine, responseMessage.Content.Headers.ContentType, responseMessage.Headers.Date, responseMessage.Headers.Location));
And here's the response from the server (same as curl):
Version compatible with .Net 4.0
var data = "{\"provider\":\"HUL\",\"payment_destination\":\"hult-applicationfee\",\"amount\":\"29000\",\"callback_url\":\"http://studentapplication.local/en/nextsteps\",\"callback_id\":\"abc1234546asas\",\"dynamic_fields\":{\"student_id\":\"32453245\",\"student_first_name\":\"Candy\",\"student_last_name\":\"Student\"}}";
var request = (HttpWebRequest)WebRequest.Create(new Uri("https://api.demo.peertransfer.com/v1/transfers"));
request.Method = "POST";
request.AllowAutoRedirect = false;
request.Accept = "*/*";
request.Headers.Add("X-Peertransfer-Digest", "zYUt+Pn0A06wsSbCrrbAZn68Aslq9CbSUAKBrUEwIzI=");
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());
Make sure you include these using statements:
using System.IO;
using System.Net;
and these are the response headers from the server: