I am working on how to upload a media file using the VoiceBase API. I tried using HttpClient ( with MultipartFormDataContent and FormUrlEncodedContent), RestClient , WebClient and WebRequest. But it didn't worked.
Following is the code I tried:
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "xxxx");
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new StringContent("http:/xx.mp3"), "media", "testFile.mp3");
HttpResponseMessage response = await client.PostAsync("https://apis.voicebase.com/v2-beta/media", form);
HttpContent responseContent = response.Content;
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
var a = reader.ReadToEndAsync();
return response;
}
API returns this error:
"status": 400,
"errors":
{
"error": "We have identified 1 error in your request: (1) Your upload was rejected because the media file not be successfully parsed (80 bytes )."
},
"reference": "3D00BCA8:A910_0A40E32A:01BB_5949122A_69009:79C6"
}
Edit
I have also tried with binary data:
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "xxxx");
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new ByteArrayContent(File.ReadAllBytes(#"C:\Users\xxxx.mp3")), "media", "xxxx.mp3");
HttpResponseMessage response = await client.PostAsync("https://apis.voicebase.com/v2-beta/media", form);
HttpContent responseContent = response.Content;
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
var a = reader.ReadToEndAsync();
return response;
}
With binary data I was getting following error:
{
"status": 400,
"errors":
{
"error": "We have identified 1 error in your request: (1) We could not download the URL"
}
,
"reference": "3D00BCA8:DFF5_0A40E32A:01BB_59491448_6F33E:79C6"
}
I needed to do this today so I've made an attempt to wrap up my work on the V3 API in a nuget package here:
https://www.nuget.org/packages/VoiceBaseV3/
When I get the time I'll get it on GitHub too
The first parameter of your form.Add(...) needs to be a data stream of the contents of the actual file, not a string. To do this you can make a new memory stream like this: new MemoryStream(File.ReadAllBytes(localfilePath))
Try this:
var content = new StreamContent(new FileStream(#"C:\Users\xxxx.mp3", FileMode.Open));
content.Headers.ContentType = new MediaTypeHeaderValue("audio/mp3");
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(content, "media", "xxxx.mp3");
If you use V3, you can generate the client code with Swagger on the language of your preference
https://voicebase.readthedocs.io/en/v3/how-to-guides/swagger-codegen.html
Related
I am not getting any response - no error, no bad request status, etc. - when I send a post request to this API route. postData is simply a JSON object. The funny thing here is this: When i send post data as a string instead of an object, I can get a response.
View the code below:
[HttpPost]
[Route("api/updateStaffs/")]
public async Task<object> UpdateStaff([FromBody] object postData)
{
string _apiUrl = "http://localhost:5000/system/getToken";
string _baseAddress = "http://localhost:5000/system/getToken";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var responseMessage = await client.PostAsync(_apiUrl, new StringContent(postData.ToString(), Encoding.UTF8, "application/json"));
if (responseMessage.IsSuccessStatusCode)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = responseMessage.Content;
return ResponseMessage(response);
}
}
return NotFound();
}
No response:
var postData = new {
user = "test"
pass = "hey"
};
var responseMessage = await client.PostAsync(_apiUrl, new StringContent(postData.ToString(), Encoding.UTF8, "application/json"));
OR
var responseMessage = await client.PostAsync(_apiUrl, new StringContent("{}", Encoding.UTF8, "application/json"));
Will get response:
var responseMessage = await client.PostAsync(_apiUrl, new StringContent("blahblah", Encoding.UTF8, "application/json"));
The receiving API is a third-party application so I am unable to verify if this error is on the other end.
Thanks.
If you dont want to use PostAsJsonAsync
You need to serialize your anonymous type to JSON, the most common tool for this is Json.NET
var jsonData = JsonConvert.SerializeObject(postData);
Then you need to construct a content object to send this data, here we can use ByteArrayContent but you can use a different type
var buffer = System.Text.Encoding.UTF8.GetBytes(jsonData);
var byteContent = new ByteArrayContent(buffer);
Then send the request
var responseMessage = await client.PostAsync(_apiUrl, byteContent);
Figured out the issue. Have to use HttpVersion10 instead of HttpVersion11.
I am trying to send a json object with a base4 encoded file to a web api service using the code below
MemoryStream target = new MemoryStream();
q.fileUpload.InputStream.CopyTo(target); //q.fileUpload is an HttpPostedFilebase pdf
var myfile= Convert.ToBase64String(target.ToArray());
var requestbody = new {
filedata = new
{
mimetype = "application/pdf",
basedata = "base64-data=" + myfile
}
};
var jsondata = JsonConvert.SerializeObject(requestbody );
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://web.base.url/");
client.DefaultRequestHeaders.Add("X-API-KEY", "SOMEAPIKEY");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "upload");
request.Content = new StringContent(jsondata, Encoding.UTF8, "application/json");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var responsetask= client.SendAsync(request);
return Json(responsetask);
But i everytime i call this i get a 406 Not Acceptable response. Anyone knows what causes it?
I'm trying to make a simple request to the Basecamp API, I'm following the instructions provided adding in a sample user agent and my credentials yet I keep getting a 403 Forbidden response back.
My credentials are definitely correct so is it a case of my request/credentials being set incorrectly?
This is what I have (removed personal info):
var httpClient = new HttpClient();
var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("User-Agent", "MyApp [EMAIL ADDRESS]") });
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]"))));
var response = await httpClient.PostAsync("https://basecamp.com/[USER ID]/api/v1/projects.json", content);
var responseContent = response.Content;
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
Console.WriteLine(await reader.ReadToEndAsync());
}
A quick look over their documentation seems to indicate that the projects.json endpoint accepts the following in the body of the POST:
{
"name": "This is my new project!",
"description": "It's going to run real smooth"
}
You're sending the User-Agent as the POST body. I'd suggest you change your code as follows:
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]")));
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp [EMAIL ADDRESS]");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
var response = await httpClient.PostAsJsonAsync(
"https://basecamp.com/[USER ID]/api/v1/projects.json",
new {
name = "My Project",
description = "My Project Description"
});
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
This posts the payload as specified in the docs and sets your user agent in the headers as it should be.
I am trying to use HttpClient to post a NameValueCollection to a specific Url. I have the code working using WebClient, but I'm trying to figure out if it is possible to do using HttpClient.
Below, you will find my working code that uses WebClient:
var payloadJson = JsonConvert.SerializeObject(new { channel, username, text });
using (var client = new WebClient())
{
var data = new NameValueCollection();
data["payload"] = payloadJson;
var response = client.UploadValues(_uri, "POST", data);
var responseText = _encoding.GetString(response);
}
I'm using this code to try to post a message to a Slack Channel using a web integration. Is there a way to implement this same functionality while using HttpClient?
The Slack error that I receive when I try to use HttpClient is "missing_text_or_fallback_or_attachment".
Thanks in advance for any help!
Using HttpClient
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://yourdomain.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var data = new NameValueCollection();
data["payload"] = payloadJson;
StringContent content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync("api/yourcontroller", content);
if (response.IsSuccessStatusCode)
{
//MessageBox.Show("Upload Successful", "Success", MessageBoxButtons.OK);
}
}
catch (Exception)
{
// ignored
}
}
While you are tagging #slack in the question, I suggest you to use Slack.Webhooks nuget package.
Example usage I found is in here;
https://volkanpaksoy.com/archive/2017/04/11/Integrating-c-applications-with-slack/
var url = "{Webhook URL created in Step 2}";
var slackClient = new SlackClient(url);
var slackMessage = new SlackMessage
{
Channel = "#general",
Text = "New message coming in!",
IconEmoji = Emoji.CreditCard,
Username = "any-name-would-do"
};
slackClient.Post(slackMessage);
I'm trying to make a simple request to the Basecamp API, I'm following the instructions provided adding in a sample user agent and my credentials yet I keep getting a 403 Forbidden response back.
My credentials are definitely correct so is it a case of my request/credentials being set incorrectly?
This is what I have (removed personal info):
var httpClient = new HttpClient();
var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("User-Agent", "MyApp [EMAIL ADDRESS]") });
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]"))));
var response = await httpClient.PostAsync("https://basecamp.com/[USER ID]/api/v1/projects.json", content);
var responseContent = response.Content;
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
Console.WriteLine(await reader.ReadToEndAsync());
}
A quick look over their documentation seems to indicate that the projects.json endpoint accepts the following in the body of the POST:
{
"name": "This is my new project!",
"description": "It's going to run real smooth"
}
You're sending the User-Agent as the POST body. I'd suggest you change your code as follows:
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]")));
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp [EMAIL ADDRESS]");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
var response = await httpClient.PostAsJsonAsync(
"https://basecamp.com/[USER ID]/api/v1/projects.json",
new {
name = "My Project",
description = "My Project Description"
});
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
This posts the payload as specified in the docs and sets your user agent in the headers as it should be.