The code block below returns me a emtpy value. But when I send a request on the postman side, the data reaches me without any problems. What do you think is the problem? Could you help? Thank you.
Code:
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new RestClient("url");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Basic mytoken");
var body = #"{" + "\n" +
#" ""size"": 1," + "\n" +
#" ""page"": 1," + "\n" +
#" ""start_date"": ""2022-01-02""," + "\n" +
#" ""end_date"": ""2022-01-03""" + "\n" +
#"}";
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
MessageBox.Show(response.Content);
REST Return Emtpy Value
Try using AddJsonBody(), Instead of AddParameter() with anonymous object
//Kindly check the type of start_date and end_date property.
var body = new { Size = 1, Page = 1, start_date="2022-01-02", end_date="2022-01-03"};
request.AddJsonBody(body);
From Documentation:
AddParameter("application/json", ..., ParameterType.RequestBody) won't work, use AddBody() instead, or better, AddJsonBody
Related
I'm trying to make HTTP request with Bearer authorization. I have a token, token is valid. Tried to do it 3 different ways: App, that request must be implemented in, POSTMAN, console app with a code generated with POSTMAN (C# - RestSharp) from the same POSTMAN call:
App POST method:
public async Task<TResponse> Post<TRequest, TResponse>(string requestUri, TRequest data)
{
LogInit(requestUri, HttpMethod.Post, data);
using (var request = new HttpRequestMessage(HttpMethod.Post, requestUri))
{
var token = await GetToken(_httpClient);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
request.Content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
using (var response = await _httpClient.SendAsync(request))
{
if (!response.IsSuccessStatusCode)
{
throw await HandleErrorResponse(response);
}
var responseObj = await response.Content.ReadAsJsonAsync<TResponse>();
return responseObj;
}
}
}
Console POST method:
static void Main(string[] args)
{
var client = new RestClient("http://***");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer xxx");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Cookie", "ARRAffinity=xxx");
var body = #"{
" + "\n" +
#" ""amisPersonId"": ***,
" + "\n" +
#" ""name"": ""***"",
" + "\n" +
#" ""surname"": ""***"",
" + "\n" +
#" ""personalCode"": ""***"",
" + "\n" +
#" ""email"": ""***"",
" + "\n" +
#" ""phoneNumber"": ""***""
" + "\n" +
#"}";
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
Requests tracked with debugger:
App request
Console app request
POSTMAN request
POSTMAN gets 200/400 reponses, App and Console app gets 401 (Unauthorized). BOTH Apps are .NET CORE apps.
assuming that you have correct token.AccessToken ,try to replace
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
with
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
I try to bring the pdf file into a standard software, wrote the code, an exception is issued because of wrong format with json although json string corresponds exactly to the specified json of api call of standard software. can you please take a look if I wrote something wrong here or if I forgot something?
I covered some information with a star
Many Thanks
IRestResponse response3;
client = new RestClient("http://***.***.***.*");
client.Authenticator = new HttpBasicAuthenticator("********", "*********");
client.Timeout = -1;
request = new RestRequest("/*****/api/******/*****/***", Method.POST);
request.AddHeader("content-type", "multipart/form-data");
request.AlwaysMultipartFormData = true;
request.AddParameter("Object", "{" +
"\"cabinet\":\"Posteingang\"," +
"\"name\":\"Posteingang\"," +
"\"objectTypeId\":\"2\"," +
"\"fields\":{" +
"\"Datum\":{\"value\":\"" + DateTime.Now.ToString("dd.MM.yyyy") + "\"}" +
"}" +
"}");
request.AddFile("file","C:/Users/*********/Documents/*********/Org.pdf","Org.pdf");
MultipartFormDataContent multipartForm = new MultipartFormDataContent();
byte[] file_bytes = File.ReadAllBytes("C:/Users/********/Documents/********/Org.pdf");
multipartForm.Add(new ByteArrayContent(file_bytes, 0, file_bytes.Length), "profile_pic", "hello1.jpg");
multipartForm.Add(new StringContent("Object"), "{" +
"\"cabinet\":\"Posteingang\"," +
"\"name\":\"Dokument\"," +
"\"objectTypeId\":\"******\"," +
"\"fields\":{" +
"\"Datum\":{\"MAIL_SUBMIT_TIME\":{\"value\":\"" + DateTime.Now.ToString("dd.MM.yyyy") + "\"},\"Typ\":" +
"{\"feld4\":{\"value\": \"Brief\"}},\"Absender\": {\"Mail_FROM\":{\"value\": \"*********\"}}}}}");
response3 = client.Execute(request);
Console.WriteLine(response3.Content);
}
}
}
How can I move a file (for example: in pdf format) that is in a folder with me locally through an api call in a folder in a document management system?
This is a small cod section of the api call that takes over the task.
client = new RestClient("http://***.***.***.*");
client.Authenticator = new HttpBasicAuthenticator("******", "******");
client.Timeout = -1;
request = new RestRequest("/*****/api/*****/*****/371 ", Method.POST);
request.AddHeader("content-type", "multipart/form-data");
request.AlwaysMultipartFormData = true;
request.AddParameter("Object", "{" +
"\"****\":\"*****\"," +
"\"name\":\"*******\"," +
"\"******\":\"2\"," +
"\"fields\":{" +
"\"*******\":{\"value\":\"" + DateTime.Now.ToString("dd.MM.yyyy") + "\"}" +
"}" +
"}");
request.AddFile("File", "C:/Users/********/Documents/****/*****/pdf.pdf");
response = client.Execute(request);
Console.WriteLine(response.Content);
}
}
}
I would have to obscure a few places with stars
Thank You
How do you upload an image to a BIM 360 Project using .NET? I have successfully been able to upload an image to a BIM 360 Project using Postman but when using the same code to perform the same function I get an error message saying:
"{\"code\":1001,\"message\":\"image has contents that are not what they are reported to be; image_content_type is invalid; \"}"
The code I used inside of .NET is the following:
var client3 = new RestClient("https://developer.api.autodesk.com/hq/v1/accounts/" + accountId + "/projects/" + targetProject + "/image");
var request3 = new RestRequest(Method.PATCH);
request3.AddHeader("cache-control", "no-cache");
request3.AddHeader("Authorization", "Bearer " + bearer.access_token);
request3.AddHeader("Content-Type", "multipart/form-data");
request3.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
request3.AddParameter("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
"------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"chunk\"; filename=\"C:\\Users\\Nathan\\Desktop\\logo.png\"\r\n" +
"Content-Type: image/png\r\n\r\n\r\n" +
"------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n" +
"Content-Disposition: form-data; name=\"type\"\r\n\r\nimage/png\r\n" +
"------WebKitFormBoundary7MA4YWxkTrZu0gW--",
ParameterType.RequestBody);
IRestResponse response3 = client3.Execute(request3);
string updatedProjectImage = response3.Content;
I used the source code here as a reference to create a PrepareRequest() function that performs all my requests. The parameters I used to complete the function are as follows:
string updatedProjectImage = PrepareRequest(
"https://developer.api.autodesk.com/hq/v1/accounts/" + accountId + "/projects/" + targetProjectId + "/image",
Method.PATCH,
new Dictionary<string, string>(),
null,
headerParams,
formParams,
fileParams,
new Dictionary<string, string>(),
"multipart/form-data");
headerParams: "Authorization", "Bearer " + bearer.access_token
formParams: "type", "image/png" (Format can change depending on the image)
fileParams: "file", fileParam
fileParam:
FileParameter fileParam = FileParameter.Create(
"chunk",
GetBytesFromFile(fileName),
Path.GetFileName(fileName),
"multipart/form-data");`
(A reference to how the GetBytesFromFile() function was made can be found in the source code. Lastly fileName includes the full address path).
Ok so I'm having a bit of trouble getting these JSON requests through to the Ebay API.
Here is the json request:
string jsonInventoryRequest = "{" +
"\"requests\": [";
int commaCount = 1;
foreach (var ep in productsToProcess)
{
jsonInventoryRequest += "{\"offers\": [{" +
"\"availableQuantity\":" + ep.EbayProductStockQuantity + "," +
"\"offerId\":\"" + ep.EbayID.ToString() + "\"," +
"\"price\": {" +
"\"currency\": \"AUD\"," +
"\"value\":\"" + ep.EbayProductPrice.ToString() + "\"" +
"}" +
"}],";
jsonInventoryRequest += "\"shipToLocationAvailability\": " + "{" +
"\"quantity\":" + ep.EbayProductStockQuantity +
"},";
jsonInventoryRequest += "\"sku\": " + ep.EbayProductSKU.ToString() + "}";
if (commaCount < productsToProcess.Count())
jsonInventoryRequest += ",";
commaCount++;
sendEbayApiRequest = true;
}
jsonInventoryRequest +=
"]" +
"}";
And the Debug.WriteLine() output of the above JSON request is :
json string = {"requests": [{"offers": [{"availableQuantity":0,"offerId":"098772298312","price": {"currency": "AUD","value":"148.39"}}],"shipToLocationAvailability": {"quantity":0},"sku": 135779},{"offers": [{"availableQuantity":1,"offerId":"044211823133","price": {"currency": "AUD","value":"148.39"}}],"shipToLocationAvailability": {"quantity":1},"sku": 133607}]}
Here is the code in C# to send the request:
var ebayAppIdSetting = _settingService.GetSettingByKey(
"ebaysetting.appid", "");
var ebayCertIdSetting = _settingService.GetSettingByKey(
"ebaysetting.certid", "");
var ebayRuNameSetting = _settingService.GetSettingByKey(
"ebaysetting.appid", "");
var stringToEncode = ebayAppIdSetting + ":" + ebayCertIdSetting;
HttpClient client = new HttpClient();
byte[] bytes = Encoding.UTF8.GetBytes(stringToEncode);
var base64string = "Basic " + System.Convert.ToBase64String(bytes);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", base64string);
var stringContent = "?grant_type=client_credentials&" + "redirect_uri=" + ebayRuNameSetting + "&scope=https://api.sandbox.ebay.com/oauth/api_scope";
var requestBody = new StringContent(stringContent.ToString(), Encoding.UTF8, "application/json");
requestBody.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = client.PostAsync("https://api.sandbox.ebay.com/identity/v1/oauth2/token", requestBody);
The output I get when I do Debug.WriteLine("response.Content = " + response.Result); is:
response.Content = StatusCode: 401, ReasonPhrase: 'Unauthorized',
Version: 1.1, Content: System.Net.Http.StreamContent, Headers: {
RlogId:
t6ldssk%28ciudbq%60anng%7Fu2h%3F%3Cwk%7Difvqn*14%3F0513%29pqtfwpu%29pdhcaj%7E%29fgg%7E%606%28dlh-1613f3af633-0xbd
X-EBAY-C-REQUEST-ID: ri=HNOZE3cmCr94,rci=6kMHBw5dW0vMDp8A
X-EBAY-C-VERSION: 1.0.0 X-EBAY-REQUEST-ID:
1613f3af62e.a096c6b.25e7e.ffa2b377!/identity/v1/oauth2/!10.9.108.107!r1esbngcos[]!token.unknown_grant!10.9.107.168!r1oauth-envadvcdhidzs5k[]
Connection: keep-alive Date: Mon, 29 Jan 2018 00:04:44 GMT
Set-Cookie: ebay=%5Esbf%3D%23%5E;Domain=.ebay.com;Path=/
WWW-Authenticate: Basic Content-Length: 77 Content-Type:
application/json }
Can anyone see where I'm going wrong. Cheers
Ok so the authentication was failing because I was sending wrong authentication token. Needed to get oauth token from application tokens.
So instead of base64 encoding token like this:
var base64string = "Basic " + System.Convert.ToBase64String(bytes);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", base64string);
I needed to do the following:
url = "https://api.sandbox.ebay.com/sell/inventory/v1/bulk_update_price_quantity";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
//request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("Authorization", "Bearer **OAUTH TOKEN GOES HERE WITHOUT ASTERIKS**");
// Send the request
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(jsonInventoryRequest);
streamWriter.Flush();
streamWriter.Close();
}
// Get the response
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
if (response != null)
{
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
// Parse the JSON response
var result = streamReader.ReadToEnd();
}
}