I search on graph api that when post video have backdated_post parameter.
But I dont know how to declare it.
On https://developers.facebook.com/docs/graph-api/reference/video, that backdated_post is json array have 3 paramter inside : backdated_time, backdated_time_granularity, hide_from_newsfeed.
And I declare [{"backdated_time": "2/12/2016"}], graph api show me error : "backdated_time not declare" or something simaliar.
Graph api I'm using that ver 2.10.
This is my code
var url = $"https://graph-video.facebook.com/v2.10/{idOrUserNameOfPage}/videos?access_token={accessTokenPage}";
using (var content =
new MultipartFormDataContent(AnotherUtils.GenerationBoundary()))
{
var streamContent = new StreamContent(streamVideo);
var videoContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync().ConfigureAwait(false));
streamContent.Dispose();
videoContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
StringContent messageContent = new StringContent(message, Encoding.UTF8);
List<dynamic> listDynamic = new List<dynamic>();
listDynamic.Add(new
{
backdated_time = datePost,
backdated_time_granularity = "none",
hide_from_newsfeed = false
});
var jsonString = JsonConvert.SerializeObject(listDynamic);
StringContent postDatePageContent = new StringContent(jsonString,Encoding.UTF8, "application/json");
content.Add(postDatePageContent, "backdated_post");
content.Add(messageContent, "description");
content.Add(videoContent, "file", "file.mp4");
var response = await _customHttpClient.PostAsync(url, content).ConfigureAwait(false);
}
And facebook show error : (#100) Invalid format for BackdatedPost, backdated_time must be defined.
Anyone help me ?? pls
I always get this error when I try to request the API.
Some details about the api : the method is POST and the parameters are correct, too (When I try it on postman, no issue)
Here is my code:
JavaScriptSerializer js = new JavaScriptSerializer();
using (WebClient client = new WebClient())
{
foreach (var ad in documents)
{
var doc = js.Serialize(ad);
var json = "{\"Message\":\"" + doc + "\"}";
var response =
client.UploadValues("apiUrl", new NameValueCollection()
{
{"json", json}
});
}
}
I read that UploadValues is POST by default. This code is called in a simple console app. Any idea why I get this error ?
Here is a working piece of code :
var doc = JsonConvert.SerializeObject(message);
var stringContent = new StringContent(
message,
UnicodeEncoding.UTF8,
"application/json");
HttpClient client = new HttpClient();
client.PostAsync("apiUrl", stringContent);
Given the following attempt to post data to a web service that generates PDF files, PDF rocket (which is awesome by the way).
I get the error Invalid URI: The uri string is too long
Why would anyone impose an arbitrary limit on POSTed data?
using (var client = new HttpClient())
{
// Build the conversion options
var options = new Dictionary<string, string>
{
{ "value", html },
{ "apikey", ConfigurationManager.AppSettings["pdf:key"] },
{ "MarginLeft", "10" },
{ "MarginRight", "10" }
};
// THIS LINE RAISES THE EXCEPTION
var content = new FormUrlEncodedContent(options);
var response = await client.PostAsync("https://api.html2pdfrocket.com/pdf", content);
var result = await response.Content.ReadAsByteArrayAsync();
return result;
}
I receive this rediculous error.
{System.UriFormatException: Invalid URI: The Uri string is too long.
at System.UriHelper.EscapeString
at System.Uri.EscapeDataString
at System.Net.Http.FormUrlEncodedContent.Encode
at System.Net.Http.FormUrlEncodedContent.GetContentByteArray
This reminds me of 640k ought to be enough... I mean really?
If, like me, you're faced with some wonky 3rd party web service that will only accept form content, you can work around the problem like this:
// Let's assume you've got your key-value pairs organised into a nice Dictionary<string, string> called formData
var encodedItems = formData.Select(i => WebUtility.UrlEncode(i.Key) + "=" + WebUtility.UrlEncode(i.Value));
var encodedContent = new StringContent(String.Join("&", encodedItems), null, "application/x-www-form-urlencoded");
// Post away!
var response = await client.PostAsync(url, encodedContent);
With a post can include the content in the http message instead of the URI. A uri has a max length of 2083 characters. You could send it as JSON in the http message instead of the URI which is the recommended way to send larger chunks of data in an HttpPost/HttpPut. I altered your code to make use of it. This assumes that your service you are contacting can work with JSON (.net Web Api out of the box should have no problem with this).
using (var client = new HttpClient())
{
// Build the conversion options
var options = new
{
value = html,
apikey = ConfigurationManager.AppSettings["pdf:key"],
MarginLeft = "10",
MarginRight = "10"
};
// Serialize our concrete class into a JSON String
var stringPayload = JsonConvert.SerializeObject(options);
var content = new StringContent(stringPayload, Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.html2pdfrocket.com/pdf", content);
var result = await response.Content.ReadAsByteArrayAsync();
return result;
}
Make sure to install newtonsoft json.
I just solved a similar problem. For me I was integrating with a backend I didn't control and had to POST file along with form data (eg customerID) as form variables. So switching to JSON or Multipart would break the backend I didn't control. The problem was that large files would cause the FormUrlEncodedContent to throw an error saying "The uri string is too long".
This is the code that solved it for me after two days of effort (note still needs to be tweaked to be ASYNC).
private string UploadFile(string filename, int CustomerID, byte[] ImageData) {
string Base64String = "data:image/jpeg;base64," + Convert.ToBase64String(ImageData, 0, ImageData.Length);
var baseAddress = new Uri("[PUT URL HERE]");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { AllowAutoRedirect = true, UseCookies = true, CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
try {
//ENCODE THE FORM VARIABLES DIRECTLY INTO A STRING rather than using a FormUrlEncodedContent type which has a limit on its size.
string FormStuff = string.Format("name={0}&file={1}&id={2}", filename, HttpUtility.UrlEncode(Base64String), CustomerID.ToString());
//THEN USE THIS STRING TO CREATE A NEW STRINGCONTENT WHICH TAKES A PARAMETER WHICH WILL FormURLEncode IT AND DOES NOT SEEM TO THROW THE SIZE ERROR
StringContent content = new StringContent(FormStuff, Encoding.UTF8, "application/x-www-form-urlencoded");
//UPLOAD
string url = string.Format("/ajax/customer_image_upload.php");
response = client.PostAsync(url, content).Result;
return response.Content.ToString();
}
catch (Exception ex) {
return ex.ToString();
}
}
}
#Mick Byrne :
Thanks - your solution worked like a charme!
Here is my complete code:
public async Task DateienSendenAsync (string PfadUndDatei, string Dateiname, String VRPinGUID, String ProjektGUID, String VRPinX, String VRPinY, String VRPinZ)
{
var client = new HttpClient();
// Create the HttpContent for the form to be posted.
var requestContent = new[] {
new KeyValuePair<string, string>("dateiname", Dateiname),
new KeyValuePair<string, string>("bild", Convert.ToBase64String(File.ReadAllBytes(PfadUndDatei))),
new KeyValuePair<string, string>("VRPinGUID", VRPinGUID),
new KeyValuePair<string, string>("ProjektGUID", ProjektGUID),
new KeyValuePair<string, string>("ebene", "ebene"),
new KeyValuePair<string, string>("raumnummer", "raumnummer"),
new KeyValuePair<string, string>("ansichtsname", "ansichtsname"),
new KeyValuePair<string, string>("VRPinX", VRPinX),
new KeyValuePair<string, string>("VRPinY", VRPinY),
new KeyValuePair<string, string>("VRPinZ", VRPinZ),
};
String url = "http://yourhomepage/path/upload.php";
var encodedItems = requestContent.Select(i => WebUtility.UrlEncode(i.Key) + "=" + WebUtility.UrlEncode(i.Value));
var encodedContent = new StringContent(String.Join("&", encodedItems), null, "application/x-www-form-urlencoded");
// Post away!
var response = await client.PostAsync(url, encodedContent);
}
For the last few hours, I've been trying to write a separate project for consuming an API. Documentation/examples for it are here.
Sadly, I can't get an "application/json" response from it, even with example values from documentation. Here's the code for my method with example values (which is copy/pasted from the documentation). I've tried a few modifications but I don't even know where to start digging.
public async void SendOrder()
{
using (var httpClient = new HttpClient { BaseAddress = baseAddress })
{
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("authorization", "Bearer 3e5cac39-7e38-4139-8fd6-30adc06a61bd");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var content = new StringContent("{ \"notifyUrl\": \"https://your.eshop.com/notify\", \"customerIp\": \"127.0.0.1\", \"merchantPosId\": \"145227\", \"description\": \"RTV market\", \"currencyCode\": \"PLN\", \"totalAmount\": \"21000\", \"products\": [ { \"name\": \"Wireless mouse\", \"unitPrice\": \"15000\", \"quantity\": \"1\" }, { \"name\": \"HDMI cable\", \"unitPrice\": \"6000\", \"quantity\": \"1\" } ]}", Encoding.UTF8, "application/json"))
{
using (var response = await httpClient.PostAsync("api/v2_1/orders/", content/*, null, "application/json"*/))
{
string responseData = await response.Content.ReadAsStringAsync();
}
}
}
}
responseData value - http://pastebin.com/t3EYyP8w
I would give RestSharp a try, can install it via Nuget. Has a easy way of doing it. http://restsharp.org/
var client = new RestClient("https://Whatever.com/api/");
client.Authenticator = new HttpBasicAuthenticator("Bearer", "YourToken");
//Add the Method you are executing from API
var request = new RestRequest("resource/{id}", Method.POST);
//Add your paramers like this
request.AddParameter("name", "value");
//Json
request.RequestFormat = DataFormat.Json;
//Execute Post
var response = client.execute(request);
//If you want to turn Json into Model
var responseModel = JsonConvert.DeserializeObject<YourObject>(response.Content);
I have a web api and I would like to post an image file + some data in order to process it correctly when it is received at the server.
The calling code looks something like this:
using(var client = new HttpClient())
using(var content = new MultipartFormDataContent())
{
client.BaseAddress = new Uri("http://localhost:8080/");
var fileContent = new ByteArrayContent(File.ReadAllBytes(fileName));
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "foo.jpg"
};
content.Add(fileContent);
FeedItemParams parameters = new FeedItemParams()
{
Id = "1234",
comment = "Some comment about this or that."
};
content.Add(new ObjectContent<FeedItemParams>(parameters, new JsonMediaTypeFormatter()), "parameters");
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data");
var result = client.PostAsync("/api/ImageServices", content).Result;
And the web api method signature looks like this:
public async Task<HttpResponseMessage> Post([FromBody]FeedItemParams parameters)
When I run this I get an UnsupportedMediaType exception. I know this has something to do with the ObjectContent, since this method worked when I was passing just an ID in the query string instead of the object in the body.
Any ideas where I'm going wrong here?
WebAPI built-in formatters only support the following media types: application/json, text/json, application/xml, text/xml and application/x-www-form-urlencoded
For multipart/form-data, which is what you are sending, take a look at Sending HTML Form Data and ASP.NET WebApi: MultipartDataMediaFormatter
Sample client
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
client.BaseAddress = new Uri("http://localhost:54711/");
content.Add(new StreamContent(File.OpenRead(#"d:\foo.jpg")), "foo", "foo.jpg");
var parameters = new FeedItemParams()
{
Id = "1234",
Comment = "Some comment about this or that."
};
content.Add(new ObjectContent<FeedItemParams>(parameters, new JsonMediaTypeFormatter()), "parameters");
var result = client.PostAsync("/api/Values", content).Result;
}
}
Sample controller if you follow the first article
public async Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
//use provider.FileData to get the file
//use provider.FormData to get FeedItemParams. you have to deserialize the JSON yourself
return Request.CreateResponse(HttpStatusCode.OK);
}