I have been trying to perform an HTTP Post request to upload an image in a silverlight application for a windows phone 7 application. The sample codes online do not get me the desired response from the API. Could anyone please provide a working code which does this?
By desired response I mean that the API responds saying that the uploaded file is in a format which cannot be read.
Thanks in advance!
Here is my code:
private void post_image(version, username,password,job-id, serviceUri)
{
if (session_free.bLoggedIn)
{
bool submit_success = false;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(serviceUri));
IsolatedStorageFileStream stream = IsolatedStorageFile.GetUserStoreForApplication().OpenFile("file.jpg", FileMode.Open);
request.PostMultiPartAsync(new Dictionary<string, object> { { "version", version }, { "username", user }, { "password", pass }, { filename, stream } }, new AsyncCallback(asyncResult =>
{
Thread.Sleep(1000);
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
Post_Result = reader.ReadToEnd();
this.Dispatcher.BeginInvoke(delegate
{
MessageBox.Show(Post_Result);
response.Close();
});
}), filename);
Thread.Sleep(1000);
}
else
{
MessageBox.Show("User not signed in! Please login to continue...", "Invalid Authentication", MessageBoxButton.OK);
}
}
public class DataContractMultiPartSerializer
{
private string boundary;
public DataContractMultiPartSerializer(string boundary)
{
this.boundary = boundary;
}
private void WriteEntry(StreamWriter writer, string key, object value, string filename)
{
if (value != null)
{
writer.Write("--");
writer.WriteLine(boundary);
if (value is IsolatedStorageFileStream)
{
IsolatedStorageFileStream f = value as IsolatedStorageFileStream;
writer.WriteLine(#"Content-Disposition: form-data; name=""{0}""; filename=""{1}""", key, filename);
writer.WriteLine("Content-Type: image/jpeg");
writer.WriteLine("Content-Length: " + f.Length);
writer.WriteLine();
writer.Flush();
Stream output = writer.BaseStream;
Stream input = f;
byte[] buffer = new byte[4096];
for (int size = input.Read(buffer, 0, buffer.Length); size > 0; size = input.Read(buffer, 0, buffer.Length))
{
output.Write(buffer, 0, size);
}
output.Flush();
writer.WriteLine();
}
else
{
writer.WriteLine(#"Content-Disposition: form-data; name=""{0}""", key);
writer.WriteLine();
writer.WriteLine(value.ToString());
}
}
}
public void WriteObject(Stream stream, object data, string filename)
{
StreamWriter writer = new StreamWriter(stream);
if (data != null)
{
if (data is Dictionary<string, object>)
{
foreach (var entry in data as Dictionary<string, object>)
{
WriteEntry(writer, entry.Key, entry.Value, filename);
}
}
else
{
foreach (var prop in data.GetType().GetFields())
{
foreach (var attribute in prop.GetCustomAttributes(true))
{
if (attribute is System.Runtime.Serialization.DataMemberAttribute)
{
DataMemberAttribute member = attribute as DataMemberAttribute;
writer.Write("{0}={1}&", member.Name ?? prop.Name, prop.GetValue(data));
}
}
}
}
writer.Flush();
}
}
}
Is there a reason you're using a multipart message?
What is the PostMultiPartAsync method you're using? Presumably it's an extension method from somewhere?
In future, try and provide the smallest, complete, piece of code which demonstrates the issue.
Anyway, sorry it's not a full working example, but here are the steps for one way to do this.
Create request and set a calback for BeginGetRequestStream
var request = (HttpWebRequest)WebRequest.Create(App.Config.ServerUris.Login);
request.Method = "POST";
request.BeginGetRequestStream(ReadCallback, request);
In that callback, get the request stream and write your data to it.
using (var postStream = request.EndGetRequestStream(asynchronousResult))
{
// Serialize image to byte array, or similar (that's what imageBuffer is)
postStream.Write(imageBuffer, 0, imageBuffer.Length);
}
Set a callback for the response from the server.
request.BeginGetResponse(ResponseCallback, request);
Check that everything worked OK on the server
private void ResponseCallback(IAsyncResult asynchronousResult)
{
var request = (HttpWebRequest)asynchronousResult.AsyncState;
using (var resp = (HttpWebResponse)request.EndGetResponse(asynchronousResult))
{
using (var streamResponse = resp.GetResponseStream())
{
using (var streamRead = new StreamReader(streamResponse))
{
string responseString = streamRead.ReadToEnd(); // Assuming that the server will send a text based indication of upload success
// act on the response as appropriate
}
}
}
}
On the server you will need to deserialize the data and turn it back into an image as appropriate.
HTH.
Related
Failed to get response for large file HTTP put create file using c#
I am using file watcher service service monitor, when user created file or folder we are uploading to cloud
if file size more than 512 MB it is taking too much time to get the response
here I am confusing here the issue with my code or server
and reason for this error
if any changes on my code suggest me.
{
var fileFolderObj1 = new FileFolder();
var postURL = apiBaseUri + "/filefolder/create/file/user/" + userId; // +"?type=file";
code = HttpStatusCode.OK;
HttpWebResponse response = null;
FileInfo f = new FileInfo(filePath);
long filesizeF = f.Length;
try
{
string selectedFile = null;
selectedFile = filePath;
var fi = System.IO.Path.GetFileName(filePath);
////commented for some reason
var postParameters = new Dictionary<string, object>();
postParameters.Add("file", new FileParameter(filePath, ""));
postParameters.Add("parentId", parentId);
postParameters.Add("newName", fi);
postParameters.Add("cloudId", cloudId);
postParameters.Add("isSecure", isSecure);
//postParameters.Add("fileSize", fi.Length);
postParameters.Add("fileSize", filesizeF);
var userAgent = "Desktop";
var formDataBoundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");
var uri = new Uri(postURL);
var createFileRequest = WebRequest.Create(uri) as HttpWebRequest;
this.SetBasicAuthHeader(createFileRequest, userId, password);
createFileRequest.ContentType = "multipart/form-data";
createFileRequest.Method = "PUT";
createFileRequest.Timeout = System.Threading.Timeout.Infinite;
createFileRequest.KeepAlive = false;/*true;*/
createFileRequest.UserAgent = userAgent;
createFileRequest.CookieContainer = new CookieContainer();
try
{
using (var requestStream = createFileRequest.GetRequestStream())
{
}
using (response = (HttpWebResponse)createFileRequest.GetResponse())
{
StreamReader(response.GetResponseStream()).ReadToEnd();
fileFolderObj1 = JsonConvert.DeserializeObject<FileFolder>(reslut);
}
}
catch (Exception exc)
{
if (response != null)
{
code = response.StatusCode;
}
}
}
catch (Exception exc)
{
}
}
}
private static readonly Encoding encoding = Encoding.UTF8;
private void WriteMultipartFormData(Dictionary<string, object> postParameters, string boundary, Stream requestStream, ILogService logService = null)
{
var needsCLRF = false;
foreach (var param in postParameters)
{
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
{
requestStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));
}
needsCLRF = true;
if (param.Value is FileParameter)
{
var fileToUpload = (FileParameter)param.Value;
// Add just the first part of this param, since we will write the file data directly to the Stream
var header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
boundary,
param.Key,
fileToUpload.FileName ?? param.Key,
fileToUpload.ContentType ?? "application/octet-stream");
requestStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));
// Write the file data directly to the Stream, rather than serializing it to a string.
FileStream fileStream = new FileStream(fileToUpload.FileName, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0,buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
logService.Debug("WRITEMULTIPART FORM DATA Bufferlent Running :{0}", bytesRead);
}
fileStream.Close();
}
else
{
var postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
param.Value);
requestStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
var footer = "\r\n--" + boundary + "--\r\n";
requestStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));
}
}
I have seen few other examples online doing the same, but I am not sure why its not working for me.
I have created a simple windows phone 7 app, which uses PhotoChooserTask.
It sends image to the server using Web Api.
Here is the code in windows phone project:
void selectphoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
var image = new Image();
image.Source = new BitmapImage(new Uri(e.OriginalFileName));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:59551/api/controllername");
request.Method = "POST";
request.ContentType = "multipart/form-data";
//private method to convert bitmap image to byte
byte[] str = BitmapToByte(image);
// Getting the request stream.
request.BeginGetRequestStream
(result =>
{
// Sending the request.
using (var requestStream = request.EndGetRequestStream(result))
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.Write(str);
writer.Flush();
}
}
// Getting the response.
request.BeginGetResponse(responseResult =>
{
var webResponse = request.EndGetResponse(responseResult);
using (var responseStream = webResponse.GetResponseStream())
{
using (var streamReader = new StreamReader(responseStream))
{
string srresult = streamReader.ReadToEnd();
}
}
}, null);
}, null);
}
On the Web API I got the following code for the POST method:
public Task<HttpResponseMessage> Post()
{
// 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 and return an async task.
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Image img = Image.FromFile(file.LocalFileName);
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
});
return task;
}
}
However I am not sure why IsMimeMultipartContent is returning false always. Even if I bypass this check, no file is saved in the App_Data folder.
Can anyone please help. Thanks.
EDITED
Based on Darrel's response I have modified the POST method in ApiController. But I still do not get any data. A blank image is created on the server. Here is my code:
public HttpResponseMessage Post()
{
var task = Request.Content.ReadAsStreamAsync();
task.Wait();
Stream requestStream = task.Result;
string root = HttpContext.Current.Server.MapPath("~/App_Data");
root = System.IO.Path.Combine(root, "xyz.jpg");
try
{
FileStream fs = System.IO.File.OpenWrite(root);
requestStream.CopyTo(fs);
fs.Close();
}
catch (Exception)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.Created;
return response;
}
You are not sending a representation that is multipart/form. You are just sending a stream of bytes which is application/octet-stream. Just use Request.Content.ReadAsStreamAsync() on the server and copy the stream to a file.
How to POST attachment to JIRA using JIRA REST API and HttpWebRequest in C#?
From the documentation under /rest/api/2/issue/{issueIdOrKey}/attachments:
POST
Add one or more attachments to an issue.
This resource expects a multipart post. The media-type multipart/form-data is defined in RFC 1867. Most client libraries have classes that make dealing with multipart posts simple. For instance, in Java the Apache HTTP Components library provides a MultiPartEntity that makes it simple to submit a multipart POST.
In order to protect against XSRF attacks, because this method accepts multipart/form-data, it has XSRF protection on it. This means you must submit a header of X-Atlassian-Token: nocheck with the request, otherwise it will be blocked.
The name of the multipart/form-data parameter that contains attachments must be "file"
A simple example to upload a file called "myfile.txt" to issue REST-123:
curl -D- -u admin:admin -X POST -H "X-Atlassian-Token: nocheck" -F "file=#myfile.txt" http://myhost.test/rest/api/2/issue/TEST-123/attachments
I have
foreach (JIRAAttachments attachm in attachments.attachments)
{
request = HttpWebRequest.Create(
logInformation.GetUri() + "/rest/api/2/issue/" + key + "/attachments"
) as HttpWebRequest;
request.Headers.Add("Authorization: Basic " + logInformation.GetEncodeAuthentication());
request.Method = "POST";
request.ContentType = "multipart/form-data";
request.Headers.Add("X-Atlassian-Token: nocheck file=#" + Path.GetFullPath(#"..\Attachments\" + attachm.filename));
request.KeepAlive = true;
request.Proxy = wp;
response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
FileStream fs = new FileStream(Path.GetFullPath(#"..\Attachments\" + attachm.filename), FileMode.Open);
byte[] write = new byte[256];
int count = fs.Read(write, 0, write.Length);
while (count > 0)
{
s.Write(write, 0, count);
count = fs.Read(write, 0, write.Length);
}
fs.Close();
s.Close();
response.Close();
}
but it returns a 404 error...
solved your problem:
var boundary = string.Format("----------{0:N}", Guid.NewGuid());
System.IO.MemoryStream content = new MemoryStream();
var writer = new StreamWriter(content);
foreach (var att in attachments)
{
writer.WriteLine("--{0}", boundary);
writer.WriteLine("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", "file", Path.GetFileName(att["filename"]));
writer.WriteLine("Content-Type: {0}", att.ContentType);
writer.WriteLine();
writer.Flush();
att.Stream.CopyTo(content);
writer.WriteLine();
}
writer.WriteLine("--" + boundary + "--");
writer.Flush();
content.Seek(0, SeekOrigin.Begin);
HttpWebRequest oRequest = null;
oRequest = (HttpWebRequest)HttpWebRequest.Create(string.Format(RestBaseURI + "issue/{0}/attachments", item.Key));
oRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
oRequest.Method = "POST";
oRequest.Headers.Add("Authorization", AuthData);
oRequest.Headers.Add("X-Atlassian-Token", "nocheck");
oRequest.UseDefaultCredentials = true;
oRequest.KeepAlive = true;
oRequest.ContentLength = content.Length;
using (var oStream = oRequest.GetRequestStream())
{
content.CopyTo(oStream);
}
using (var oResponse = (HttpWebResponse)oRequest.GetResponse())
{
using (var reader = new StreamReader(oResponse.GetResponseStream()))
{
var responseData = reader.ReadToEnd();
var data = JObject.Parse(responseData);
}
}
PS: thanks2mod to delete my previous post! nice ...
There was a couple of mistakes in the OP's code.
With the snippet provided by #mabu and the code I found on http://www.briangrinstead.com/blog/multipart-form-post-in-c, here's a *functional** Code Block to Upload attachment to Jira.
public bool AddAttachments(string issueKey, IEnumerable<string> filePaths)
{
string restUrl = Jira.FormatRestUrl(m_JiraId, true);
string issueLinkUrl = String.Format("{0}/issue/{1}/attachments", restUrl, issueKey);
var filesToUpload = new List<FileInfo>();
foreach (var filePath in filePaths)
{
if (!File.Exists(filePath))
{
Jira.LogError("File '{0}' doesn't exist", filePath);
return false;
}
var file = new FileInfo(filePath);
if (file.Length > 10485760) // TODO Get Actual Limit
{
Jira.LogError("Attachment too large");
return false;
}
filesToUpload.Add(file);
}
if (filesToUpload.Count <= 0)
{
Jira.LogWarning("No file to Upload");
return false;
}
return PostMultiPart(issueLinkUrl, filesToUpload);
}
private Boolean PostMultiPart(string restUrl, IEnumerable<FileInfo> filePaths)
{
HttpWebResponse response = null;
HttpWebRequest request = null;
try
{
var boundary = string.Format("----------{0:N}", Guid.NewGuid());
var content = new MemoryStream();
var writer = new StreamWriter(content);
foreach (var filePath in filePaths)
{
var fs = new FileStream(filePath.FullName, FileMode.Open, FileAccess.Read);
var data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
fs.Close();
writer.WriteLine("--{0}", boundary);
writer.WriteLine("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"", filePath.Name);
writer.WriteLine("Content-Type: application/octet-stream");
writer.WriteLine();
writer.Flush();
content.Write(data, 0, data.Length);
writer.WriteLine();
}
writer.WriteLine("--" + boundary + "--");
writer.Flush();
content.Seek(0, SeekOrigin.Begin);
request = WebRequest.Create(restUrl) as HttpWebRequest;
if (request == null)
{
Jira.LogError("Unable to create REST query: {0}", restUrl);
return false;
}
request.Method = "POST";
request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
request.Accept = "application/json";
request.Headers.Add("Authorization", "Basic " + m_EncodedCredential);
request.Headers.Add("X-Atlassian-Token", "nocheck");
request.ContentLength = content.Length;
using (Stream requestStream = request.GetRequestStream())
{
content.WriteTo(requestStream);
requestStream.Close();
}
using (response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
var reader = new StreamReader(response.GetResponseStream());
Jira.LogError("The server returned '{0}'\n{1}", response.StatusCode, reader.ReadToEnd());
return false;
}
return true;
}
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
var reader = new StreamReader(errorResponse.GetResponseStream());
Jira.LogError("The server returned '{0}'\n{1}).", errorResponse.StatusCode, reader.ReadToEnd());
}
}
if (request != null)
{
request.Abort();
}
return false;
}
finally
{
if (response != null)
{
response.Close();
}
}
}
I really didn't want to deal with all that boundary stuff, so here's my shot at it. This works against Confluence whose API looks identical to Jira.
Thanks to Michael Teper at ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient
and Jeff Caron (above).
var contents = "some long HTML that I wanted to upload";
var fileName = "Some fancy file name.html";
using (var client = new HttpClient())
{
var uri = new Uri(URL);
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = authorization;
client.DefaultRequestHeaders.Add("X-Atlassian-Token", "nocheck");
var uriPath = String.Format(AttachmentPath, pageId);
var content = new MultipartFormDataContent();
var fileContent = new StringContent(contents);
// also tested to work:
// var fileContent = new ByteArrayContent(Encoding.UTF8.GetBytes(contents));
content.Add(fileContent, "file", fileName);
var response = await client.PostAsync(uriPath, content);
if (response.IsSuccessStatusCode)
{
return TaskResult.Success(null, response.ReasonPhrase);
}
else
{
return TaskResult.Failure("Service responded with Status Code: " + response.StatusCode + Environment.NewLine + "Reason Phrase: " + response.ReasonPhrase);
}
}
You're also able to do with Restsharp as follow
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Jira
using RestSharp;
using RestSharp.Authenticators;
namespace Jira
{
class Program
{
static void Main(string[] args)
{
var client = new RestClient("http://{URL}/rest/api/2");
var request = new RestRequest("issue/", Method.POST);
client.Authenticator = new HttpBasicAuthenticator("user", "pass");
var issue = new Issue
{
fields =
new Fields
{
description = "Issue Description",
summary = "Issue Summary",
project = new Project { key = "KEY" },
issuetype = new IssueType { name = "ISSUE_TYPE_NAME" }
}
};
request.AddJsonBody(issue);
var res = client.Execute<Issue>(request);
if (res.StatusCode == HttpStatusCode.Created)
{
Console.WriteLine("Issue: {0} successfully created", res.Data.key);
#region Attachment
request = new RestRequest(string.Format("issue/{0}/attachments", res.Data.key), Method.POST);
request.AddHeader("X-Atlassian-Token", "nocheck");
var file = File.ReadAllBytes(#"C:\FB_IMG_1445253679378.jpg");
request.AddHeader("Content-Type", "multipart/form-data");
request.AddFileBytes("file", file, "FB_IMG_1445253679378.jpg", "application/octet-stream");
var res2 = client.Execute(request);
Console.WriteLine(res2.StatusCode == HttpStatusCode.OK ? "Attachment added!" : res2.Content);
#endregion
}
else
Console.WriteLine(res.Content);
}
}
public class Issue
{
public string id { get; set; }
public string key { get; set; }
public Fields fields { get; set; }
}
public class Fields
{
public Project project { get; set; }
public IssueType issuetype { get; set; }
public string summary { get; set; }
public string description { get; set; }
}
public class Project
{
public string id { get; set; }
public string key { get; set; }
}
public class IssueType
{
public string id { get; set; }
public string name { get; set; }
}
}
The whole code is on gist https://gist.github.com/gandarez/c2c5b2b27dbaf62a0d634253529bcb59
I'm using some of the code I found on here to POST an image to a server. The problem is that I am not receiving the Json response that I should be, instead I'm getting the ol' SERVER NOT FOUND response in my "ResponseReady" callback. (EDIT: Turns out it was just my parameters, this code works perfectly fine.)
Here is the class I am using to make the POST
public class PostSubmitter
{
public string url { get; set; }
public Dictionary<string, object> parameters { get; set; }
string boundary = "----------" + DateTime.Now.Ticks.ToString();
HttpWebRequest webRequest;
public void Submit()
{
// Prepare web request...
webRequest = WebRequest.CreateHttp(url);
webRequest.Method = "POST";
webRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
webRequest.BeginGetRequestStream(new AsyncCallback(RequestReady), webRequest);
}
private void RequestReady(IAsyncResult asynchronousResult)
{
using (Stream postStream = webRequest.EndGetRequestStream(asynchronousResult))
{
writeMultipartObject(postStream, parameters);
}
webRequest.BeginGetResponse(new AsyncCallback(ResponseReady), webRequest);
}
private void ResponseReady(IAsyncResult asynchronousResult)
{
try
{
using (var response =
(HttpWebResponse)webRequest.EndGetResponse(asynchronousResult))
using (var streamResponse = response.GetResponseStream())
using (var streamRead = new StreamReader(streamResponse))
{
var responseString = streamRead.ReadToEnd();
var success = response.StatusCode == HttpStatusCode.OK;
if (responseString != null)
{
//JObject comes from Newtonsoft.Json ddl. This is a good one if your working with json
JObject jsonResponse = JObject.Parse(responseString);
//Do stuff with json.....
}
}
}
catch (Exception e)
{
if (e.Message == "The remote server returned an error: NotFound.")
{
webRequest.Abort();
Deployment.Current.Dispatcher.BeginInvoke(delegate() { MessageBox.Show("Unable to connect to server at this time, please try again later"); });
}
else
Deployment.Current.Dispatcher.BeginInvoke(delegate() { MessageBox.Show("Unable to upload photo at this time, please try again later"); });
return;
}
}
public void writeMultipartObject(Stream stream, object data)
{
using (StreamWriter writer = new StreamWriter(stream))
{
if (data != null)
{
foreach (var entry in data as Dictionary<string, object>)
{
WriteEntry(writer, entry.Key, entry.Value);
}
}
writer.Write("--");
writer.Write(boundary);
writer.WriteLine("--");
writer.Flush();
}
}
private void WriteEntry(StreamWriter writer, string key, object value)
{
if (value != null)
{
writer.Write("--");
writer.WriteLine(boundary);
if (value is byte[])
{
byte[] ba = value as byte[];
writer.WriteLine(#"Content-Disposition: form-data; name=""{0}""; filename=""{1}""", key, "sentPhoto.jpg");
writer.WriteLine(#"Content-Type: application/octet-stream");
writer.WriteLine(#"Content-Type: image / jpeg");
writer.WriteLine(#"Content-Length: " + ba.Length);
writer.WriteLine();
writer.Flush();
Stream output = writer.BaseStream;
output.Write(ba, 0, ba.Length);
output.Flush();
writer.WriteLine();
}
else
{
writer.WriteLine(#"Content-Disposition: form-data; name=""{0}""", key);
writer.WriteLine();
writer.WriteLine(value.ToString());
}
}
}
}
Using this class we can then make a simple POST to the server with the following lines of code:
Dictionary<string, object> postData = new Dictionary<string, object>()
{
{"file", byteArrayOfImage}
//You can add other parameters here
};
PostSubmitter postToServer = new PostSubmitter() { url = getPicturePostUrl(), parameters = postData };
postToServer.Submit();
There are so many questions out there on this... you'd think they'd make it easier to do complex web requests....
Thanks in advance for your helpful comments or feel free to ask a question.
Well this code actually works perfectly. I just didn't have one of the required parameters so the server was rejecting the request.
I am new to Windows Phone 7 application development. I am trying to call a URL in my program using POST method which takes some parameters. After the successful post I am supposed to get the response in JSON format. But I am not getting the response. The code I am using is:
public void Submit()
{
// Prepare web request...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri(someUrl, UriKind.Absolute));
myRequest.Method = "POST";
myRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
}
public string url { get; set; }
private Dictionary<string, string> _parameters = new Dictionary<string, string>();
public Dictionary<string, string> parameters
{
get { return _parameters; }
set { _parameters = value; }
}
string boundary = "----------" + DateTime.Now.Ticks.ToString();
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
parameters.Add("userid", "0");
parameters.Add("locationid", "0");
writeMultipartObject(postStream, parameters);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
public void writeMultipartObject(Stream stream, object data)
{
StreamWriter writer = new StreamWriter(stream);
if (data != null)
{
foreach (var entry in data as Dictionary<string, string>)
{
WriteEntry(writer, entry.Key, entry.Value);
}
}
writer.Write("--");
writer.Write(boundary);
writer.WriteLine("--");
writer.Flush();
}
private void WriteEntry(StreamWriter writer, string key, object value)
{
if (value != null)
{
writer.Write("--");
writer.WriteLine(boundary);
if (value is byte[])
{
byte[] ba = value as byte[];
writer.WriteLine(#"Content-Disposition: form-data; name=""{0}""; filename=""{1}""", key, "sentPhoto.jpg");
writer.WriteLine(#"Content-Type: application/octet-stream");
//writer.WriteLine(#"Content-Type: image / jpeg");
writer.WriteLine(#"Content-Length: " + ba.Length);
writer.WriteLine();
writer.Flush();
Stream output = writer.BaseStream;
output.Write(ba, 0, ba.Length);
output.Flush();
writer.WriteLine();
}
else
{
writer.WriteLine(#"Content-Disposition: form-data; name=""{0}""", key);
writer.WriteLine();
writer.WriteLine(value.ToString());
}
}
}
I cannot find what the real problem is. Anybody out there to help me out?
Maybe not a 'real' answer, but I always use: http://postclient.codeplex.com/ when dealing with Posts. This just to be sure I don't write any faults with the Request code.
Just give it a try.
This example come from http://northernlights.codeplex.com
/// <summary>
/// Send error report (exception) to HTTP endpoint.
/// </summary>
/// <param name="uri">The Endpoint to report to.</param>
/// <param name="exception">Exception to send.</param>
public void SendExceptionToHttpEndpoint(string uri, ExceptionContainer exception)
{
if (!this.AllowAnonymousHttpReporting)
{
return;
}
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.BeginGetRequestStream(
r =>
{
try
{
HttpWebRequest request1 = (HttpWebRequest)r.AsyncState;
Stream postStream = request1.EndGetRequestStream(r);
string info = string.Format("{0}{1}{2}{1}AppVersion: {3}{1}", exception.Message, Environment.NewLine, exception.StackTrace, exception.AppVersion);
string postData = "&exception=" + HttpUtility.UrlEncode(info);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
request1.BeginGetResponse(
s =>
{
try
{
HttpWebRequest request2 = (HttpWebRequest)s.AsyncState;
HttpWebResponse response = (HttpWebResponse)request2.EndGetResponse(s);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
string response2 = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch
{
}
},
request1);
}
catch
{
}
},
webRequest);
}
catch
{
}
}
It shows you how to post.
WP7 ships with the "Reactive Extensions" that is helpful with asynch interactions in general. This sample http://wp7guide.codeplex.com shows how to use it for HTTP Posts (and other things)
Caveat: the sample is for a rather advanced app, and is meant to show many other things like unit testing, using the MVVM pattern, etc. It might be more sophisticated than what you need.
I got the solution as:
{
Dictionary<string, object> param = new Dictionary<string, object>();
param.Add(DataHolder.USER_ID, "0");
param.Add(DataHolder.DEFAULT_LOCATION_ID, "0");
PostClient proxy = new PostClient(param);
proxy.DownloadStringCompleted += new PostClient.DownloadStringCompletedHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri(DataHolder.mainConfigFetchUrl, UriKind.Absolute));
}
void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
//Process the result...
string data = e.Result;
}
}
For PostClient we will need a WindowsPhonePostClient.dll which can be obtained from http://postclient.codeplex.com/