I'm developing an application on windows phone 8.1 in c# that can take a picture and send it to a server (in base64) with a post request.
So my problem is that i can't find a method which still work for include my image base64 in the body on my request and send it to my server.
private async void validPicture_Click(object sender, RoutedEventArgs e)
{
Encode("ms-appx:///xx/xxx.jpg");
try
{
var client = new Windows.Web.Http.HttpClient();
var uri = new Uri("http://x.x.x.x:x/picture/");
string pathBase64 = Encode("ms-appx:///xx/xxx.jpg").ToString();
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("type", "recognition");
HttpFormUrlEncodedContent formContent = new HttpFormUrlEncodedContent(pairs);
Windows.Web.Http.HttpResponseMessage response = await client.PostAsync(uri, formContent);
string content = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
}
}
catch (Exception eu)
{
}
}
If you are a question or need more information please tell me.
Thanks for your time.
First of all you have to read image file from storage and convert bytes to base64 string.
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(PHOTO_PATH));
byte[] rawBytes;
using (Stream stream = await file.OpenStreamForReadAsync())
{
rawBytes = new byte[stream.Length];
await stream.ReadAsync(rawBytes, 0, rawBytes.Length);
}
string base64Content = Convert.ToBase64String(rawBytes);
Then you have to make request with that content. I'm not sure how yours server accept requests but here is example of sending request with that string in content.
var httpClient = new Windows.Web.Http.HttpClient();
IBuffer content = CryptographicBuffer.ConvertStringToBinary(base64Content, BinaryStringEncoding.Utf8);
var request = new HttpBufferContent(content);
HttpResponseMessage response = await httpClient.PostAsync(new Uri(SERVER_URL), request);
Related
I'm currently using Pushbullet API and need to upload a file.
I can successfully get an upload url as specified in the docs using this method:
public static async Task<Uploads> GetUploadUrl(string file_name, string file_type)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Access-Token", AccessToken);
var json = new JObject
{
["file_name"] = file_name,
["file_type"] = file_type
};
var result = await client.PostAsync(new Uri(_uploadUrl, UriKind.RelativeOrAbsolute), new HttpStringContent(json.ToString(), UnicodeEncoding.Utf8, "application/json"));
if (result.IsSuccessStatusCode)
{
var textresult = await result.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Uploads>(textresult);
}
}
return null;
}
The problem is when I try to upload the file. I'm currently using this method:
public static async Task<bool> UploadFile(StorageFile file, string upload_url)
{
try
{
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
var content = new MultipartFormDataContent();
if (file != null)
{
var streamData = await file.OpenReadAsync();
var bytes = new byte[streamData.Size];
using (var dataReader = new DataReader(streamData))
{
await dataReader.LoadAsync((uint)streamData.Size);
dataReader.ReadBytes(bytes);
}
var streamContent = new ByteArrayContent(bytes);
content.Add(streamContent);
}
client.DefaultRequestHeaders.Add("Access-Token", AccessToken);
var response = await client.PostAsync(new Uri(upload_url, UriKind.Absolute), content);
if (response.IsSuccessStatusCode)
return true;
}
catch { return false; }
return false;
}
but I get a Http 400 error. What's the right way to upload a file using multipart/form-data in a UWP app?
HTTP 400 error indicates Bad Request, it means the request could not be understood by the server due to malformed syntax. In the other word, the request sent by the client doesn't follow server's rules.
Let's look at the document, and we can find in the example request it uses following parameter:
-F file=#cat.jpg
So in the request, we need to set the name for the uploaded file and the name should be "file". Besides, in this request, there is no need to use access token. So you can change your code like following:
public static async Task<bool> UploadFile(StorageFile file, string upload_url)
{
try
{
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
var content = new MultipartFormDataContent();
if (file != null)
{
var streamData = await file.OpenReadAsync();
var bytes = new byte[streamData.Size];
using (var dataReader = new DataReader(streamData))
{
await dataReader.LoadAsync((uint)streamData.Size);
dataReader.ReadBytes(bytes);
}
var streamContent = new ByteArrayContent(bytes);
content.Add(streamContent, "file");
}
//client.DefaultRequestHeaders.Add("Access-Token", AccessToken);
var response = await client.PostAsync(new Uri(upload_url, UriKind.Absolute), content);
if (response.IsSuccessStatusCode)
return true;
}
catch { return false; }
return false;
}
Then your code should be able to work. You will get a 204 No Content response and UploadFile method will return true.
I have a Api Post method that I want to be able to accept any file type and that looks like this:
[HttpPost]
public async Task<IHttpActionResult> Post()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
if (provider.Contents.Count != 1)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest,
"You must include exactly one file per request."));
}
var file = provider.Contents[0];
var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
var buffer = await file.ReadAsByteArrayAsync();
}
This works in fiddler when I try to post an image to it. However, I'm writing a client library and I have a method that looks like this:
public string PostAttachment(byte[] data, Uri endpoint, string contentType)
{
var request = (HttpWebRequest)WebRequest.Create(endpoint);
request.Method = "POST";
request.ContentType = contentType;
request.ContentLength = data.Length;
var stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
var response = (HttpWebResponse) request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
Whenever I try to post an image using this, I'm getting a UnsuportedMediaType error. I'm assuming it's because my image isn't Multi Part Content? Is there an easy way to make my request of the correct type?
If I have to change my web api post method, is there an easy way of doing that without writing files to the server and keeping it in memory?
The MultipartFormDataContent from the System.Net.Http namespace will allow you to post multipart form data.
private async Task<string> PostAttachment(byte[] data, Uri url, string contentType)
{
HttpContent content = new ByteArrayContent(data);
content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
using (var form = new MultipartFormDataContent())
{
form.Add(content);
using(var client = new HttpClient())
{
var response = await client.PostAsync(url, form);
return await response.Content.ReadAsStringAsync();
}
}
}
i want to use catchoom in c# , but not able to find any sample could any one please provide any sample code if have.
i have got this sample of curl
curl -F "image=#CATask1-Correct.png" -F "token=sometoken" https://r.catchoom.com/v1/search
Can some one covert this to c# ?
I tried to convert it as shown below:
Here's my code:
public static async Task<string> Upload(byte[] image)
{
using (var client = new HttpClient())
{
// string boundary = "---XXX---";
using (var content = new MultipartFormDataContent())
{
string token = "sometoken";
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(token);
writer.Flush();
stream.Position = 0;
// adding Token and Image to the request
content.Add(new StreamContent(stream), "token");
content.Add(new StreamContent(new MemoryStream(image)), "bilddatei", "upload.jpg");
using (
var message = await client.PostAsync("https://r.catchoom.com/v1/search", content))
{
var input = await message.Content.ReadAsStringAsync();
return input;
}
}
}
}
then I called the method in the on-click event handler:
private async void mybtn_Click(object sender, RoutedEventArgs e)
{
// converting the image to a byte array
BitmapImage bitmapImage = new BitmapImage(new Uri("http://www.familyfuntwincities.com/wp-content/uploads/2013/09/apple_red_1_clipart.png?s=128&g=1"));
RandomAccessStreamReference rasr = RandomAccessStreamReference.CreateFromUri(bitmapImage.UriSource);
var streamWithContent = await rasr.OpenReadAsync();
byte[] buffer = new byte[streamWithContent.Size];
await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None);
// calling the upload method
string output = await Upload(buffer);
mytext1.Text = output;
}
but I keep getting "image is missing" error from the catchoom server although I managed to upload the image to other servers in the same way ( without the token part of course).
My question is: How to add multipule part content? what's the right boundary between the Token part and the image part in order to be recognized by catchoom?
Here is what worked for me:
public static async Task<string> Test(string token, Stream stream, string fileName)
{
HttpClient client = new HttpClient();
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StringContent(token), "token");
content.Add(new StreamContent(stream), "image", fileName);
var resp = await client.PostAsync("https://r.catchoom.com/v1/search", content);
return await resp.Content.ReadAsStringAsync();
}
If you wanted to use the image you listed in your sample, here is how I would fetch it:
HttpClient client = new HttpClient();
var stream = await client.GetStreamAsync("http://www.familyfuntwincities.com/wp-content/uploads/2013/09/apple_red_1_clipart.png?s=128&g=1");
return await Test("<SOME_TOKEN_VALUE>", stream, "apple.png");
However the API claims that the image is unsupported due to alpha transparency. You can find some other samples that show you how to strip alpha transparency if that is important. The above code worked fine for images that don't have alpha transparency.
I need to send some parameters to a php server using post method in WP8 app and get response in json format. I've tried everything that I found on stackoverflow and other sites, still could not.
The last code piece I come up with is:
public static async void GetData(string url, string data)
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(new Uri(url), new StringContent(data));
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
MessageBox.Show(responseBody); // just showing the response for now
}
It shows a message from the server (which is an error stating some fields are missing) that it actually communicates with the server but the problem is with sending data. I call the above method like:
GetData("http_address_here", "?action=REGISTER&email=asc#fsdf.com&password=54561wefwe&firstname=sdfsdf&lastname=sdfsdf&picture=10");
But I saw an example sending data in xml. Possibly the mistake is about calling the method. Having seen tens of sample codes and trying everything, I really got confused about it. Any help is appreciated.
I finally managed to solve the problem. Thanks everyone for helping. The working code is below, it uses POST method and the resulting json object is stored as a string.
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("email", "qewfwef"),
new KeyValuePair<string, string>("password", "qewfwef"),
new KeyValuePair<string, string>("firstname", "qewfwef"),
new KeyValuePair<string, string>("lastname", "qewfwef"),
new KeyValuePair<string, string>("picture", "123456")
};
var httpClient = new HttpClient(new HttpClientHandler());
HttpResponseMessage response = await httpClient.PostAsync(url, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
MessageBox.Show(responseString.ToString()); // just to see what we get
Can you try this
public static async Task<string> SendRequestPostResponse()
{
try
{
var postRequest = (HttpWebRequest)WebRequest.Create("your Url Here");
postRequest.ContentType = "application/x-www-form-urlencoded"; // Whichever content type you want to POST
postRequest.Method = "POST";
using (var requestStream = await postRequest.GetRequestStreamAsync())
{
byte[] postDataArray = Encoding.UTF8.GetBytes("your data here"); // Data for the POST request here
await requestStream.WriteAsync(postDataArray, 0, postDataArray.Length);
}
WebResponse postResponse = await postRequest.GetResponseAsync();
if (postResponse != null)
{
var postResponseStream = postResponse.GetResponseStream();
var postStreamReader = new StreamReader(postResponseStream);
string response = await postStreamReader.ReadToEndAsync();
return response;
}
return null;
}
}
HTTPWebRequest would be another alternative.
what I want is simple, I want to read a text file from my website via my application, I managed to do this in C# but not in metro apps, here my code in C#
WebClient client = new WebClient();
Stream stream = client.OpenRead(strURL);
StreamReader reader = new StreamReader(stream);
String content = reader.ReadToEnd();
return content;
besides the above code I also tried the code below, but still failed
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(strURL);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
byte[] buf = new byte[1000];
StringBuilder sb = new StringBuilder();
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.Unicode.GetString(buf, 0, count);
sb.Append(tempString);
}
}
return sb.ToString();
I think the problem is in the WebClient and GetResponse () which is not known in metro apps
You should be able to use System.Net.Http.HttpClient and HttpResponseMessage, as they are included on http://msdn.microsoft.com/en-us/library/windows/apps/hh454046.aspx.
There is an example on http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx:
static async void Main()
{
try
{
// Create a New HttpClient object.
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method in following line
// string body = await client.GetStringAsync(uri);
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
var httpClient = new HttpClient();
var text = await httpClient.GetStringAsync(uri);
Wrapped up in an async method of course