We are trying to upload image to Twitter via silverlight code in WP7. We are able to post the message but not the image.
We tried all including download of their library but not getting the hint.
In following link,
https://dev.twitter.com/docs/api/1/post/statuses/update_with_media
there is one point which we are not able to set.
"Unlike POST statuses/update, this method expects raw multipart data. Your POST request's Content-Type should be set to multipart/form-data with the media[] parameter "
I am not getting it how to put it.
Can anyone please guide me or provide sample for image upload?
If your photo is called LoadedPhoto, you could create a memory stream from it
MemoryStream ms = new MemoryStream();
LoadedPhoto.SaveJpeg(ms, LoadedPhoto.PixelWidth, LoadedPhoto.PixelHeight, 0, 100);
Create OAuthCredentials object according to the authentication details you have acquired
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = Common.TwitterSettings.ConsumerKey,
ConsumerSecret = Common.TwitterSettings.ConsumerKeySecret,
Token = file.AccessToken,
TokenSecret = file.AccessTokenSecret,
Version = "1.0"
};
Create a RestClient and a RestRequest
var restClient = new RestClient
{
Authority = "https://upload.twitter.com"
};
var restRequest = new RestRequest
{
Credentials = credentials,
Path = "/1/statuses/update_with_media.xml",
Method = Hammock.Web.WebMethod.Post
};
Set the stream position to 0
ms.Position = 0;
Add fields to RestRequest
restRequest.AddField("status", message);
restRequest.AddFile("media[]", "ScreenShot.png", ms, "image/jpeg");
And then begin request
restClient.BeginRequest(restRequest, callback);
callback is a callback method for the request.
Taken from my blog post, see there for more details if you're interested.
Related
I have an .net core WEB API method that needs to call another external API (java) which expects .zip file. When try to access the external API via Postman by attaching the file, it is working fine (getting expected response). However when i pass the same parameters via my WEB API code, it is throwing 403-Forbidden error.
Please let me know if i am missing anything....
Thanks in advance!!!
request-header
request-body-file-attached
response-403-error
API code: for connecting to api:
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("pane", "forward");
parameters.Add("forward_path", "/store/execute");
parameters.Add("csrf", "1996fe6b2d0c97a8a0db725a10432d83");
parameters.Add("data_format", "binary");
newContent = new FormUrlEncodedContent(parameters);
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent con;// = new StringContent("file_name");
//form.Add(con, "file_name");
form.Add(newContent);
var str = new FileStream("D:\\dummy\\xmlstore.zip", FileMode.Open);
con = new StreamContent(str);
con.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file_name",
FileName = "xmlstore.zip"
};
con.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
form.Add(con);
client.DefaultRequestHeaders.Add("Cookie", "JSESSIONID=05DEB277E294CBF73288F2E24682C7EE;");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("br"));
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("user-agent", "1"));
var resp = client.PostAsync("java-api", con).Result;
I am creating a web api to allow download files through POST. There is no need for UI. I am sending Byte array along with the Filename in a JSON as follows.
{
"FileName": "xxxyyyzzz.pdf",
"FileType": "Pricing",
"FileID": 12457,
"ContentInByteArray":
"JVBERi0xLjMNCiXi48QoNCnN0YXJ0eHJlZg0KMjcxNA0KJSVFT0YNCg==",
"ExceptionMessage": ""
}
The File content is actually converted into Byte array and set to "ContentInByteArray". Is this a good approach. Or Do I need any improvisation.
Please suggest.
You use send byte[] array when you need post file or image content or may be token content and handle them at API.
var request = new SomePostRequest
{
Id = 1,
Content = File.ReadAllBytes(filename); // read content file to byte[]
};
jsonSerializer.Serialize(bson, request);
var client = new HttpClient
{
BaseAddress = new Uri("http://www.server.com")
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/bson"));
var byteArrayContent = new ByteArrayContent(stream.ToArray());
byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/bson");
var result = await client.PostAsync(
"api/upload", byteArrayContent);
I am implementing a Xamarin Form mobile app to allow post photo to Drupal using service module node resources. http://xxxx.com/{endpoint}/node/4/attach_file
i able to post from POSTMAN with
I tried to implement with c# HttpClient but keep getting response like "401 :Missing required argument field_name"
Please help on my code:
var httpClient = new HttpClient(new NativeMessageHandler());
httpClient.Timeout.Add(new TimeSpan(0, 0, 30));
httpClient.BaseAddress = new Uri(BaseAddress);
var content = new MultipartFormDataContent();
var streamContent = new StreamContent(g_media.GetStream());
streamContent.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse("form-data");
streamContent.Headers.ContentDisposition.Parameters.Add(new NameValueHeaderValue("field_name", "field_receipt_image"));
content.Add(streamContent,"files[file]");
var response = await httpClient.PostAsync("node/4/attach_file", content);
response.EnsureSuccessStatusCode();
I had the same issue and used RestSharp to resolve it. Here is the code I used to upload a file to Drupal:
var restClient = new RestClient("http:XXXXXX/attach_file");
var request = new RestRequest(Method.POST);
request.AddFile("files[file]", fileName);
request.AddParameter("field_name", field);
IRestResponse response = restClient.Execute(request);
I want my bot to send a PDF file to the user. I have the PDF as a base64 string and tried to send it through an attachment:
Attachment attachment1 = new Attachment();
attachment1.Name = "name.pdf";
attachment1.ContentType = "application/pdf";
attachment1.ContentUrl = "data:application/pdf;base64," + base64String;
var m = context.MakeMessage();
m.Attachments.Add(attachment1);
m.Text = "File";
await context.PostAsync(m);
Within the emulator, it just doesn't work but in the channels Telegram and Facebook (which I need), the bot just outputs an error...
Has someone already succeed in it?
Note: Using an HTTP address works fine, but I need to use the base64 string
As this method in botframework call sendDocument method of Telegram, and this method in its document property get http url or a file_id, so you can't pass base64String to this method as a valid document type.
You can follow the valid type of the document passing into the telegram in this link (also, see the following image).
The pdf file must be embedded resource. Hope it help.
if (this.channelid == "telegram")
{
var url = string.Format("https://api.telegram.org/bot{0}/sendDocument", Settings.tokentelegram);
Assembly _assembly;
Stream file;
using (var form = new MultipartFormDataContent())
{
form.Add(new StringContent(this.chat_id, Encoding.UTF8), "chat_id");
_assembly = Assembly.GetExecutingAssembly();
file = _assembly.GetManifestResourceStream("Namespace.FolderResourses.name.pdf");
form.Add(new StreamContent(file), "document", "name.pdf");
using (var client = new HttpClient())
{
await client.PostAsync(url, form);
}
}
}
Using RestSharp 104.4.0 on Xamarin 4.2.2.
I cannot figure out why RestSharp does not add the parameter to a POST request. I am hitting a REST API that takes both GET and POST.
Not working POST:
var request_post = new RestRequest ("folder/endpoint.php", Method.POST);
request_post.AddParameter("ref", "some/value");
response = client.Execute(request_post);
Console.WriteLine (response.Content);
Error is saying that ref parameter is required.
Working GET:
var request_get = new RestRequest ("folder/endpoint.php", Method.GET);
request_get.AddParameter("ref", "some/value");
response = client.Execute(request_get);
Console.WriteLine (response.Content);
Update:
It may be adding the parameter but I need to add the parameters as a form.
Thanks, Matt.
// POST request.
//
// This method does not work!
// var request_post = new RestRequest ("folder/endpoint.php", Method.POST);
// request_post.AddParameter("ref", "some/value");
//
// This method does work.
var endpoint = String.Format("folder/endpoint.php?{0}={1}",
"ref", "some/value");
var request_post = new RestRequest (endpoint, Method.POST);
response = client.Execute(request_post);
// Print out headers.
foreach (var header in response.Headers){
Console.WriteLine(header);
}
// Print response.
Console.WriteLine(response.Content)