j3k01
Member
- Joined
- Sep 6, 2023
- Messages
- 12
- Programming Experience
- 1-3
Hi, I'm struggling with post to api on endpoint that requires formdata content-type. I dont have idea why json in postman works, but in my code not. I'll be glad for any type of help
post to api:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using System.Text;
using System.Net;
using Newtonsoft.Json;
using mesaCon;
namespace MesaConnection
{
class Program
{
private const string MesaApiUrl = "url";
private const string MesaApiUrlPost = "url2";
static async Task Main(string[] args)
{
try
{
var authToken = await GetAuthToken();
byte[] Blob64byte = Encoding.ASCII.GetBytes("qwerty");
var requestData = new Root
{
Metadata = new Metadata
{
Data = new Data
{
Name = "Najnowsza27",
Category = "5000025",
MainLang = "6",
UploadFile = new UploadFile
{
FileName = "Mesa n3.pdf",
Description = "Mesa n3",
Blob64 = Blob64byte
},
AREQ = "2",
SendNotification = "2",
S01_1 = "3000033",
S01_3 = "3000263",
Ambito = new List<string> { "3000756", "3000744" }
}
},
DeleteFile = new List<object>(),
Files = new List<object>()
};
string jsonRequest = JsonConvert.SerializeObject(requestData);
Console.WriteLine("JSON Request:");
Console.WriteLine(jsonRequest);
var postMessage = await ApiPostRequest(authToken, jsonRequest);
Console.WriteLine("Response from POST Request:");
Console.WriteLine(postMessage);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught: " + ex.Message);
}
}
private static async Task<string> GetAuthToken()
{
using (var client = new HttpClient())
{
var baseUri = "url";
var username = "1";
var password = "2!";
var clientId = "3";
var formData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("an_login_type_id", "1"),
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("username", username),
};
var content = new FormUrlEncodedContent(formData);
var response = await client.PostAsync(baseUri + "/auth/token", content);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
var jwtToken = JObject.Parse(responseContent)["access_token"].ToString();
return jwtToken;
}
throw new Exception("Nie udało się uzyskać tokena JWT.");
}
}
private static async Task<string> ApiGetRequest(string authToken)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
var endpoint = await client.GetAsync(MesaApiUrl);
if (endpoint.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
throw new Exception("Brak autoryzacji. Sprawdź swoje uwierzytelnienie.");
}
endpoint.EnsureSuccessStatusCode();
string responseBody = await endpoint.Content.ReadAsStringAsync();
return responseBody;
}
}
private static async Task<string> ApiPostRequest(string authToken, string jsonRequest)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
string boundary = "Test";
JObject jsonDataObject = JObject.Parse(jsonRequest);
var content = new MultipartFormDataContent(boundary);
foreach (var property in jsonDataObject["Metadata"]["Data"].Children())
{
content.Add(new StringContent(property.First.ToString()), property.Path);
}
string fileName = jsonDataObject["Metadata"]["Data"]["UploadFile"]["FileName"].ToString();
byte[] fileData = Convert.FromBase64String(jsonDataObject["Metadata"]["Data"]["UploadFile"]["Blob64"].ToString());
var fileContent = new ByteArrayContent(fileData);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
content.Add(fileContent, "file", fileName);
content.Headers.Remove("Content-Type");
content.Headers.TryAddWithoutValidation("Content-Type", $"multipart/form-data; boundary={boundary}");
var response = await client.PostAsync(MesaApiUrlPost, content);
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new Exception("Brak autoryzacji. Sprawdź swoje uwierzytelnienie.");
}
return await response.Content.ReadAsStringAsync();
}
}
}
}