I'm trying to Upload Track to sound cloud. So far i'm successfully able to get auth token but when i tried to 'PostAsync' it throws exception
A Task was canceled. I have also set the timeout value but still the same error. Issue seems to be something wrong with what i'm doing. Below is the code which i'm using and i have taken it from stack overflow but with no luck.
private async Task<bool> StartUploadAsync(PubVidoInfo pubStuff)
{
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.ConnectionClose = true;
httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Mixcraft", "1.0"));
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
ByteArrayContent titleContent = new ByteArrayContent(Encoding.UTF8.GetBytes(pubStuff.title));
ByteArrayContent descriptionContent = new ByteArrayContent(Encoding.UTF8.GetBytes(pubStuff.description));
ByteArrayContent sharingContent = null;
if (pubStuff.publishedFileState == PubFileState.PF_Public)
{
sharingContent = new ByteArrayContent(Encoding.UTF8.GetBytes("public"));
}
else
{
sharingContent = new ByteArrayContent(Encoding.UTF8.GetBytes("private"));
}
ByteArrayContent byteArrayContent = new ByteArrayContent(File.ReadAllBytes(pubStuff.pubFilePath));
byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(titleContent, "track[title]");
content.Add(descriptionContent, "track[description]");
content.Add(sharingContent, "track[sharing]");
content.Add(byteArrayContent, "track[asset_data]", Path.GetFileName(pubStuff.pubFilePath));
try
{
HttpResponseMessage message = await httpClient.PostAsync(new Uri("https://api.soundcloud.com/tracks"), content);
if (message.IsSuccessStatusCode)
{
PubUploadStatus = PubUploadStatus.US_Finished;
}
else
{
PubUploadStatus = PubUploadStatus.US_Failed;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
PubUploadStatus = PubUploadStatus.US_Failed;
}
return true;
}
Is there any thing i'm doing ? Can any one point out the issue in particular code.
Regards,
Related
I have Get API for getting data, when it is hitting from Postman it gives response properly,
but while hitting from the code it skipping the code. I am using HttpClient().
My code for hitting the api is below :
I didn't get the point here why this happening.
public async Task<string> GetAsync(string uri, string serverAddress = "")
{
try
{
string id = System.DateTime.Now.ToString("hhmmss");
HttpClient httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 0, 0, 0, Timeout);
httpClient.BaseAddress = new Uri(serverAddress);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
var responseMessage = await httpClient.GetAsync(new Uri(uri));
var responseContent = await responseMessage.Content.ReadAsStringAsync();
if (!responseMessage.IsSuccessStatusCode)
{
throw new RestException
{
ResponseCode = (int)responseMessage.StatusCode,
ResponseContent = responseContent
};
}
return responseContent;
}
catch (Exception ex)
{
throw new Exception($"The Get request timed out. Exception :- {ex.Message}");
}
}
From this line -->
var responseMessage = await httpClient.GetAsync(new Uri(uri));
my code is skipping
Edit -->
After Testing more, I also got no exception after the timeout.
comment below line in your code
httpClient.BaseAddress = new Uri(serverAddress);
and pass full url instead of new Uri(uri) in below line
var responseMessage = await httpClient.GetAsync(new Uri(uri));
Try the following:
public async Task<string> GetAsync(string uri, string serverAddress = "")
{
try
{
string id = System.DateTime.Now.ToString("hhmmss");
HttpClient httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 0, 0, 0, Timeout);
httpClient.BaseAddress = new Uri(serverAddress);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
var responseMessage = await httpClient.GetAsync(uri);
var responseContent = await responseMessage.Content.ReadAsStringAsync();
if (!responseMessage.IsSuccessStatusCode)
{
throw new RestException
{
ResponseCode = (int)responseMessage.StatusCode,
ResponseContent = responseContent
};
}
return responseContent;
}
catch (Exception ex)
{
throw new Exception($"The Get request timed out. Exception :- {ex.Message}");
}
}
Ensure you add await before calling this method in your code and check if the full URL that's actually called has been build correctly. You can just pass a string into the GetAsync() method, no need to create a new URI.
I keep getting this error when trying to use POST Method.
I need to get from the API a list of certificates into a LIST, I know that "lista" is null right now, since I can´t get the API to bring me the lists yet.
public async Task<List<Certificaciones>> grillaCertificadosAsync(int id)
{
List<Certificaciones> lista = new List<Certificaciones>();
var cert = new jsonCert()
{
idProyecto = id
};
var id1 = JsonConvert.SerializeObject(cert);
var content = new StringContent(id1, Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var result = await client.PostAsync("https://certificacionesbuho.mendoza.gov.ar/api/BuhoBlanco/GetInfoCert", content);
var responseBody = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
return lista;
This is the API.
[Route("Api/BuhoBlanco/GetInfoCert")]
[System.Web.Http.ActionName("GetInfoCert")]
[System.Web.Http.HttpPost]
public Respuesta GetInfoCert([FromBody]infoCertRequest infoCert)
{
Respuesta rta = new Respuesta();
try
{
BuhoServicio.ServicioBuhoBlanco _servicio = new BuhoServicio.ServicioBuhoBlanco();
rta.Exito = true;
rta.StatusCode = HttpStatusCode.OK;
rta.Data = _servicio.infoCertificados(infoCert.idProyecto);
//((IDisposable)_servicio).Dispose();
return rta;
}
catch (Exception ex)
{
rta.Error = ex.Message;
rta.Exito = false;
rta.StatusCode = HttpStatusCode.InternalServerError;
return rta;
}
}
IMHO route should be like this
[HttpPost("~/Api/BuhoBlanco/GetInfoCert")]
public Respuesta GetInfoCert([FromBody]infoCertRequest infoCert)
I am trying to call an api(POST method) with HttpClient.PostAsJsonAsync. However, it stopped at httpClient.PostAsJsonAsync without any exception.
The source code as below:
public static async Task<oResult> PostApi(string JSON_sObject, string sEnd_Url) {
oResult oResult = new oResult();
var Data = JsonConvert.DeserializeObject(JSON_sObject);
var Url = "http://localhost:44340/" + sEnd_Url;
HttpClient httpClient = new HttpClient();
try {
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await httpClient.PostAsJsonAsync(new Uri(Url), Data); // it stopped here
if (response.IsSuccessStatusCode)
{
var sResponse_content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<oResult>(sResponse_content);
}
else
{
return oResult;
}
}
catch (Exception ex)
{
LogFile(ex);
return oResult;
}
}
Please advice me if any issue from the source code.
Thank you
you should not trying serialize deserialize twice
remove from your code
var Data = JsonConvert.DeserializeObject(JSON_sObject);
and replace
HttpResponseMessage response = await httpClient.PostAsJsonAsync(new Uri(Url), Data);
with this
var content = new StringContent(JSON_sObject, Encoding.UTF8, "application/json");
var response = await client.PostAsync(sEnd_Url, content);
also fix base httpclient address
var baseUri= #"http://localhost:44340";
using HttpClient client = new HttpClient { BaseAddress = new Uri(baseUri) };
try {
I am trying to call simple POST API to create a Zendesk Ticket from Console App.
I create C# core console app in VS2019 and pasted simple code which should create New Ticket.
code work in other app but in console app, app just log out from debug...
call never goes...
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://testhelp.zendesk.com/api/v2/tickets.json"))
{
try
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("test#test.com:testPassword"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
request.Content = new StringContent("{\"ticket\": {\"subject\": \"My first Ticket!\", \"comment\": { \"body\": \"The ticket is from API.\" }}}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
Console.WriteLine(response);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
What am I missing?
Async calls are frigid mistresses in some cases.
A good option is to make your main program async and therefore able to await tasks. The issue here is with GUI if that is what you actually have when you get away from the command line I am not sure how well it plays with UI threads, but here is the example. Which is much more elegant.
static async Task Main(string[] args)
{
var TicketTask = await createTicket();
}
async static Task<string> createTicket()
{
var content = "unknown error";
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://testhelp.zendesk.com/api/v2/tickets.json"))
{
try
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("test#test.com:testPassword"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
request.Content = new StringContent("{\"ticket\": {\"subject\": \"My first Ticket!\", \"comment\": { \"body\": \"The ticket is from API.\" }}}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);
content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
//Console.WriteLine(response);
}
catch (Exception ex)
{
content = ex.Message;
}
}
}
return content;
}
Quick-and-dirty-simple-solution (which I would not suggest for production) is to monitor content within the main loop as a global variable where you fill it on success or failure.
static string content = "";
static void Main(string[] args)
{
var loopcount = 0;
var t = new Task(createTicket);
t.Start();
while(content == "" && loopcount < 50000)
{
System.Threading.Thread.Sleep(100);
loopcount++;
}
}
async static void createTicket()
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://testhelp.zendesk.com/api/v2/tickets.json"))
{
try
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("test#test.com:testPassword"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
request.Content = new StringContent("{\"ticket\": {\"subject\": \"My first Ticket!\", \"comment\": { \"body\": \"The ticket is from API.\" }}}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);
content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
//Console.WriteLine(response);
}
catch (Exception ex)
{
content = ex.mesage;
}
}
}
}
I am with a problem. I have 2 WebApi´s . The webapi2 get the data from DB and return the IMAGE. Here, its ok and working. If i try on browser, show me the image or if i change, the byte array.
The problem is with the Webapi1 that calls this webapi2. I always receive the HttpResponseMessage with false for IsSuccessStatusCode. The error is 500 internal server error.
I am a newbie and i don´t know what to do...i already tryed a lot of things
public async Task<HttpResponseMessage> GetFoto(string exemplo, string exemple2)
{
HttpClientHandler handler = new HttpClientHandler()
{
UseDefaultCredentials = true,
};
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://192.111.56.1:1762/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("api/Tr/Test?exemplo="+exemplo+"&pk="+pk+"");
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsByteArrayAsync().Result;
var stream = new MemoryStream(data);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return response;
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
return null;
}
}
}
My webapi that Works and return me a Image:
//connections code that doesn´t matter....
try
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new MemoryStream(imgBytes);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return result;
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.Gone);
}
The error is because when you pass a value on the browser, they change some carachters... So, you are passing 2 values... you have to use
On the webapi 1
var MIRACLE = Uri.EscapeDataString(exemplo);
And at the webapi2
var MIRACLE2 = Uri.UnescapeDataString(MIRACLE)
As per your code, the web api 1 will accept only the media type = "application/json".
This is because you have added the below code :
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
So either you remove the line of code or change it to "image/jpeg" from "application/json".