I am interested in sending some data from my C# code to a php page, I can already send a single variable and even two, but when it comes to a 2D array i'm already clueless.
My goal is to send the 4 2D arrays within the arguments to a php page via the string postData and echo back the data into one really long string (I can handle the rest when I'm able to do this) I need to send the 2D arrays so i can process them in the php file,
Here is my code: (This is the only method i know for HTTP communication)
private String communicateToServer(String serverHostname, String[,] disk = null,
String[,] hdd = null, String[,] nic = null, String[,] ram = null)
{
try
{
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "user=" + SystemInformation.ComputerName; // user = a string containing the hostname
byte[] data = encoding.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverHostname); // its a link to a page
request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
String returnValue = sr.ReadToEnd();
sr.Close();
stream.Close();
return returnValue;
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
return " ";
}
Thank you and have a nice day =)
I turned My array into a big XML string then passed it to this function as a single string and used this value as post data:
My Arguments:
private String communicateToServer(String serverHostname, String disk = null, String hdd = null,String nic = null, String ram = null)
How my Post Data looks like:
if (disk == null && hdd == null && nic == null && ram == null)
{
postData = "user=" + SystemInformation.ComputerName; // user = a string containing the hostname
}
else
{
postData = "user=" + SystemInformation.ComputerName + "&disk=" + disk + "&hdd=" + hdd + "&nic=" + nic + "&ram" + ram;
}
String values for disk,hdd,nic,ram (example):
<hddInfo>
<hddInterface>
<model>TOSHIBA MQ01ABD075</model>
<interfaceType>IDE</interfaceType>
<name>\\.\PHYSICALDRIVE0</name>
<partitions>3</partitions>
<serialNumber> X 52F801S4</serialNumber>
<status>OK</status>
</hddInterface>
<hddInterface>
<model>SD Card</model>
<interfaceType>USB</interfaceType>
<name>\\.\PHYSICALDRIVE1</name>
<partitions>1</partitions>
<serialNumber></serialNumber>
<status>OK</status>
</hddInterface>
Related
I want to send some json data using this code to a distant server (Rest, outside my control), following the way I'm sending it :
I create the url and the request method first :
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(gUrlDot);
request.Method = "POST";
Dictionary<String, String> lDictionary = new Dictionary<String, String>();
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Dot lDot= new Dot();
serviceContext lserviceContext = new serviceContext();
items litems = new items();
lDot.rad = pClient;
lDictionary.Add("companyId", "00230");
lDictionary.Add("treatmentDate", lGlobals.FormatDateYYYYMMDD());
lDictionary.Add("country", "FR");
lDictionary.Add("language", "fr");
lDictionary.Add("Id", "test");
litems.contextItem = lDictionary;
lDot.serviceContext = lserviceContext;
lDot.serviceContext.items = litems;
String Input=_Tools.JsonSerializer(lDot);
log.Debug("Input Dot " + Input);
Byte[] byteArray = encoding.GetBytes(Input);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
When i'm getting here it crashes with an execption : Error 500 !
try
{
using (var response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
string output = response.ToString();
lTrace.AppendLine("-Flux Json recu => " + response.StatusCode + " " + length);
log.Debug("Output Dot " + output);
}
log.Info(LogsHelper.LogHeader("End processing Get list ", pClient, Service.SrvGetList, "", lResponse.StatusCode, lResponse.StatusLabel, lResponse.ResponseObject, ref lTrace));
}
catch (Exception ex)
{
lResponse.StatusCode = StatusCodes.ERROR_COMMUNICATION;
log.Error(LogsHelper.LogHeader("End processing Get list", pClient, Service.SrvGetList, "", lResponse.StatusCode, ex.Message, lResponse.ResponseObject, ref lTrace));
}
return lResponse;
}
what am i missing here?
A 500 error means there's a problem on the server you're making the request to. You'll need to check to make sure two things;
1) Make sure your request is properly formatted, and doesn't have any surprises or invalid values for the requested resource.
2) that the server you want to talk to CAN get requests, and that its up-to-date (if you control the client).
In either case, the most common reason for a 500 is that something outside of your control has gone wrong on the client server.
I am trying to send image using web service. I am converting image first to base64 string and using web request Post method sending to server. Here is my code.
try
{
qry = "Select ProductImage From tbl_Product where ProductOnlineID=0";
dt = db.DataTable(qry);
foreach (DataRow dr in dt.Rows)
{
string fileName = dr["ProductImage"].ToString();
string storeLocation = Application.StartupPath + #"\product_image\";
if (System.IO.File.Exists(storeLocation + fileName))
{
Image image = Image.FromFile(storeLocation + fileName);
MemoryStream m = new MemoryStream();
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
string url_upload_imag = #"http://Myserver/api/offline/json/1.0/index.php";
string rq = "token=" + apikey + #"&json_data={%22method%22:%22uploadProductImagesLocal%22,%22data%22:[{%22imgName%22:%22" + fileName + "%22,%22imgString%22:%22" + base64String + "%22}]}";
WebRequest request = WebRequest.Create(url_upload_imag);
request.Method = "POST";
request.ContentLength = rq.Length;
byte[] array = new UTF8Encoding().GetBytes(rq);
request.ContentType = "application/x-www-form-urlencoded";
using (Stream str = request.GetRequestStream())
{
str.Write(array, 0, array.Length);
using (WebResponse ws = request.GetResponse())
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(RootObject_Image));
RootObject_Image obj = (RootObject_Image)jsonSerializer.ReadObject(ws.GetResponseStream());
MessageBox.Show("Done" + fileName + obj.data);
}
}
}
}
}
catch (WebException ex)
{
MessageBox.Show("Error in Sending Image:" + ex.ToString(), "Error:", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
My Problem is..When I run the application I get Time out Error..I've tried everything setting timeout to infinite doesn't work for me. My base64 string is also correct.
Web service is created in php. what could be error?? and if there is any error, from which side it could be, PHP or C#?
I need make a multipart post request to a Rest service to send an image and a string but I can't do the code work. this is the code and I make a comment with capital letters where I get the exception and the exception message in the catch block.
public async Task<bool> addImages(Project project)
{
bool success = false;
string uuid = project.uuid;
if (uuid.Equals(""))
{
return success;
}
mUploadedImages = 0;
mProject = project;
string service = "service/imagen-project/add";
string serviceURL = mBaseURL + "/pwpcloud/" + service;
//build the REST request
// HTTP web request
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceURL);
httpWebRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
httpWebRequest.Method = "POST";
httpWebRequest.AllowWriteStreamBuffering = false;
//Calculate the total size of the upload content.
string boundaryStringLine = "\r\n--" + boundary + "\r\n";
byte[] boundaryStringLineBytes = Encoding.UTF8.GetBytes(boundaryStringLine);
string lastBoundaryStringLine = "\r\n--" + boundary + "--\r\n";
byte[] lastBoundaryStringLineBytes = Encoding.UTF8.GetBytes(lastBoundaryStringLine);
// Get the byte array of the myFileDescription content disposition
string myFileDescriptionContentDisposition = String.Format(
"Content-Dis-data; name=\"{0}\"\r\n\r\n","project");
byte[] myFileDescriptionContentDispositionBytes = Encoding.UTF8.GetBytes(myFileDescriptionContentDisposition);
byte[] uuidBytes = Encoding.UTF8.GetBytes(project.uuid);
string fileUrl = "isostore:/" + project.Name + "_ID" + project.ID + "_Pictures/Pic_1.jpg";
string fileName = project.Name + "_ID" + project.ID + "_Pictures/Pic_1.jpg";
string myFileContentDisposition = String.Format("Content-Dis-data;name=\"{0}\"; " +
"filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", "myFile", Path.GetFileName(fileUrl), "image/png");
byte[] myFileContentDispositionBytes = Encoding.UTF8.GetBytes(myFileContentDisposition);
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
var fileStream = isoStore.OpenFile(fileName, FileMode.Open, FileAccess.Read);
byte[] imageBytes = new byte[fileStream.Length];
// Calculate the total size of the HTTP request
long totalRequestBodySize = boundaryStringLineBytes.Length * 2 + lastBoundaryStringLineBytes.Length + myFileDescriptionContentDispositionBytes.Length + uuidBytes.Length +
+myFileContentDispositionBytes.Length + imageBytes.Length;
httpWebRequest.ContentLength = totalRequestBodySize;
//Set cripted authorization -- WORKS FINE
setAuthorization(httpWebRequest, service, WEBSERVICE_REQUEST_TYPE_POST);
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream, httpWebRequest.EndGetRequestStream, null))
{
// Send the file description content disposition over to the server
await stream.WriteAsync(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
await stream.WriteAsync(myFileDescriptionContentDispositionBytes, 0, myFileDescriptionContentDisposition.Length);
await stream.WriteAsync(uuidBytes, 0, uuidBytes.Length);
// Send the file content disposition over to the server
await stream.WriteAsync(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
await stream.WriteAsync(myFileContentDispositionBytes, 0, myFileContentDispositionBytes.Length);
fileStream.Read(imageBytes, 0, imageBytes.Length);
await stream.WriteAsync(imageBytes, 0, imageBytes.Length);
fileStream.Close();
// Send the last part of the HTTP request body
await stream.WriteAsync(lastBoundaryStringLineBytes, 0, lastBoundaryStringLineBytes.Length);
}
try
{
var responseTask = Task.Factory.FromAsync<WebResponse>(httpWebRequest.BeginGetResponse, httpWebRequest.EndGetResponse, null);
using (var response = (HttpWebResponse)await responseTask) //I GET THE EXCEPCION HERE (
{
string data;
// Read the response into a Stream object.
Stream responseStream = response.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
}
}
catch (Exception e)
{
string err = e.Message; // err = "The remote server returned an error: NotFound" but the ServiceURL is ok
throw;
}
return success;
}
I could run this in a desktop program using C++ but I couldn't find any class to do it in C# using the same "sctructure". This is the C++ code:
void WebServicesClient::addImages(PW::Project *project){
QString uuid = project->getCloudUUID();
if (uuid.isEmpty()) /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
return;
mUploadedImages = 0;
mProject = project;
QNetworkRequest request;
QString serviceURL = mBaseURL+"/service/imagen-project/add";
request.setUrl(QUrl(serviceURL));
// request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart textPart;
textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"project\""));
textPart.setBody(uuid.toAscii());
QHttpPart imagePart;
imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/png"));
QString fileName = project->getImages().at(0)->getFileName();
QString header = "form-data; name=\"file\"";
header += "; filename=\"" + fileName + "\"";
imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(header));
QFile *file = new QFile(project->getImages().at(0)->getFullPath());
file->open(QIODevice::ReadOnly);
imagePart.setBodyDevice(file);
file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart
multiPart->append(textPart);
multiPart->append(imagePart);
setAuthorization(request, "service/imagen-project/add", WEBSERVICE_REQUEST_TYPE_POST);
QObject::connect(mNetwork, SIGNAL(finished(QNetworkReply *)),
this, SLOT(onAddImageFinished(QNetworkReply*)));
emit statusChanged(0, "Uploading " + project->getImages().at(0)->getFileName());
QNetworkReply *reply = mNetwork->post(request,multiPart);
}
I hope someone can help me.
Thanks everyone!
In C# i need to POST some data to a web server using HTTP. I keep getting errors returned by the web server and after sniffing throught the data I dound that the problem is that thew Content-type header is still set to "text/html" and isn't getting changed to "application/json; Charset=UTF-8" as in my program. I've tried everything I can think of that might stop it getting changed, but am out of ideas.
Here is the function that is causing problems:
private string post(string uri, Dictionary<string, dynamic> parameters)
{
//Put parameters into long JSON string
string data = "{";
foreach (KeyValuePair<string, dynamic> item in parameters)
{
if (item.Value.GetType() == typeof(string))
{
data += "\r\n" + item.Key + ": " + "\"" + item.Value + "\"" + ",";
}
else if (item.Value.GetType() == typeof(int))
{
data += "\r\n" + item.Key + ": " + item.Value + ",";
}
}
data = data.TrimEnd(',');
data += "\r\n}";
//Setup web request
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(Url + uri);
wr.KeepAlive = true;
wr.ContentType = "application/json; charset=UTF-8";
wr.Method = "POST";
wr.ContentLength = data.Length;
//Ignore false certificates for testing/sniffing
wr.ServerCertificateValidationCallback = delegate { return true; };
try
{
using (Stream dataStream = wr.GetRequestStream())
{
//Send request to server
dataStream.Write(Encoding.UTF8.GetBytes(data), 0, data.Length);
}
//Get response from server
WebResponse response = wr.GetResponse();
response.Close();
}
catch (WebException e)
{
MessageBox.Show(e.Message);
}
return "";
}
The reason i'm getting problems is because the content-type stays as "text/html" regardless of what I set it as.
Thanks in advence.
As odd as this might sound, but this worked for me:
((WebRequest)httpWebRequest).ContentType = "application/json";
this changes the internal ContentType which updates the inherited one.
I am not sure why this works but I would guess it has something to do with the ContentType being an abstract property in WebRequest and there is some bug or issue in the overridden one in HttpWebRequest
A potential problem is that you're setting the content length based on the length of the string, but that's not necessarily the correct length to send. That is, you have in essence:
string data = "whatever goes here."
request.ContentLength = data.Length;
using (var s = request.GetRequestStream())
{
byte[] byteData = Encoding.UTF8.GetBytes(data);
s.Write(byteData, 0, data.Length);
}
This is going to cause a problem if encoding your string to UTF-8 results in more than data.Length bytes. That can happen if you have non-ASCII characters (i.e. accented characters, symbols from non-English languages, etc.). So what happens is your entire string isn't sent.
You need to write:
string data = "whatever goes here."
byte[] byteData = Encoding.UTF8.GetBytes(data);
request.ContentLength = byteData.Length; // this is the number of bytes you want to send
using (var s = request.GetRequestStream())
{
s.Write(byteData, 0, byteData.Length);
}
That said, I don't understand why your ContentType property isn't being set correctly. I can't say that I've ever seen that happen.
I'm using the Facebooks Javascript API to develop an application that will need to be able to post an image to a users wall.
That part of the app needs to be server-side as far as I can tell, since it needs to post the image data as "multipart/form-data".
Note: It's not the simple version using "post", but the real "photos" method.
http://graph.facebook.com/me/photos
I think I'm facing two problems, a .NET and a Facebook problem:
Facebook problem: I'm not quite sure if all parameters should be send as multipart/form-data (including the access_token and message). The only code example there is uses the cUrl util/application.
.NET problem: I have never issued multipart/form-data requests from .NET , and I'm not sure if .NET automatically creates the mime-parts, or if I have to encode the parameters in some special way.
It's a bit hard to debug, since the only error response I get from the Graph API is "400 - bad request".
Below is the code as it looked when I decided to write this question (yes, it's a bit verbose :-)
The ultimate answer would of course be a sample snippet posting an image from .NET, but I can settle for less.
string username = null;
string password = null;
int timeout = 5000;
string requestCharset = "UTF-8";
string responseCharset = "UTF-8";
string parameters = "";
string responseContent = "";
string finishedUrl = "https://graph.facebook.com/me/photos";
parameters = "access_token=" + facebookAccessToken + "&message=This+is+an+image";
HttpWebRequest request = null;
request = (HttpWebRequest)WebRequest.Create(finishedUrl);
request.Method = "POST";
request.KeepAlive = false;
//application/x-www-form-urlencoded | multipart/form-data
request.ContentType = "multipart/form-data";
request.Timeout = timeout;
request.AllowAutoRedirect = false;
if (username != null && username != "" && password != null && password != "")
{
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential(username, password).GetCredential(new Uri(finishedUrl), "Basic");
}
//write parameters to request body
Stream requestBodyStream = request.GetRequestStream();
Encoding requestParameterEncoding = Encoding.GetEncoding(requestCharset);
byte[] parametersForBody = requestParameterEncoding.GetBytes(parameters);
requestBodyStream.Write(parametersForBody, 0, parametersForBody.Length);
/*
This wont work
byte[] startParm = requestParameterEncoding.GetBytes("&source=");
requestBodyStream.Write(startParm, 0, startParm.Length);
byte[] fileBytes = File.ReadAllBytes(Server.MapPath("images/sample.jpg"));
requestBodyStream.Write( fileBytes, 0, fileBytes.Length );
*/
requestBodyStream.Close();
HttpWebResponse response = null;
Stream receiveStream = null;
StreamReader readStream = null;
Encoding responseEncoding = System.Text.Encoding.GetEncoding(responseCharset);
try
{
response = (HttpWebResponse) request.GetResponse();
receiveStream = response.GetResponseStream();
readStream = new StreamReader( receiveStream, responseEncoding );
responseContent = readStream.ReadToEnd();
}
finally
{
if (receiveStream != null)
{
receiveStream.Close();
}
if (readStream != null)
{
readStream.Close();
}
if (response != null)
{
response.Close();
}
}
Here is a sample of how to upload binary data. But an uploading to /me/photos won't publish the image into wall :( The image saving into your app's album. I'm stuck on how to announce it in the feed. Yet another way is to post an image into "Wall Album", by URL=="graph.facebook.com/%wall-album-id%/photos". But didn't found any way to create sucha album (user creates it when uploading an image via the site).
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
uploadRequest = (HttpWebRequest)WebRequest.Create(#"https://graph.facebook.com/me/photos");
uploadRequest.ServicePoint.Expect100Continue = false;
uploadRequest.Method = "POST";
uploadRequest.UserAgent = "Mozilla/4.0 (compatible; Windows NT)";
uploadRequest.ContentType = "multipart/form-data; boundary=" + boundary;
uploadRequest.KeepAlive = false;
StringBuilder sb = new StringBuilder();
string formdataTemplate = "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n";
sb.AppendFormat(formdataTemplate, boundary, "access_token", PercentEncode(facebookAccessToken));
sb.AppendFormat(formdataTemplate, boundary, "message", PercentEncode("This is an image"));
string headerTemplate = "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n";
sb.AppendFormat(headerTemplate, boundary, "source", "file.png", #"application/octet-stream");
string formString = sb.ToString();
byte[] formBytes = Encoding.UTF8.GetBytes(formString);
byte[] trailingBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
long imageLength = imageMemoryStream.Length;
long contentLength = formBytes.Length + imageLength + trailingBytes.Length;
uploadRequest.ContentLength = contentLength;
uploadRequest.AllowWriteStreamBuffering = false;
Stream strm_out = uploadRequest.GetRequestStream();
strm_out.Write(formBytes, 0, formBytes.Length);
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)imageLength))];
int bytesRead = 0;
int bytesTotal = 0;
imageMemoryStream.Seek(0, SeekOrigin.Begin);
while ((bytesRead = imageMemoryStream.Read(buffer, 0, buffer.Length)) != 0)
{
strm_out.Write(buffer, 0, bytesRead); bytesTotal += bytesRead;
gui.OnUploadProgress(this, (int)(bytesTotal * 100 / imageLength));
}
strm_out.Write(trailingBytes, 0, trailingBytes.Length);
strm_out.Close();
HttpWebResponse wresp = uploadRequest.GetResponse() as HttpWebResponse;
}
Cleaned up class method using #fitz's code. Pass in a byte array or a file path for the image. Pass in an album id if uploading to an existing album.
public string UploadPhoto(string album_id, string message, string filename, Byte[] bytes, string Token)
{
// Create Boundary
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
// Create Path
string Path = #"https://graph.facebook.com/";
if (!String.IsNullOrEmpty(album_id))
{
Path += album_id + "/";
}
Path += "photos";
// Create HttpWebRequest
HttpWebRequest uploadRequest;
uploadRequest = (HttpWebRequest)HttpWebRequest.Create(Path);
uploadRequest.ServicePoint.Expect100Continue = false;
uploadRequest.Method = "POST";
uploadRequest.UserAgent = "Mozilla/4.0 (compatible; Windows NT)";
uploadRequest.ContentType = "multipart/form-data; boundary=" + boundary;
uploadRequest.KeepAlive = false;
// New String Builder
StringBuilder sb = new StringBuilder();
// Add Form Data
string formdataTemplate = "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n";
// Access Token
sb.AppendFormat(formdataTemplate, boundary, "access_token", HttpContext.Current.Server.UrlEncode(Token));
// Message
sb.AppendFormat(formdataTemplate, boundary, "message", message);
// Header
string headerTemplate = "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n";
sb.AppendFormat(headerTemplate, boundary, "source", filename, #"application/octet-stream");
// File
string formString = sb.ToString();
byte[] formBytes = Encoding.UTF8.GetBytes(formString);
byte[] trailingBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
byte[] image;
if (bytes == null)
{
image = File.ReadAllBytes(HttpContext.Current.Server.MapPath(filename));
}
else
{
image = bytes;
}
// Memory Stream
MemoryStream imageMemoryStream = new MemoryStream();
imageMemoryStream.Write(image, 0, image.Length);
// Set Content Length
long imageLength = imageMemoryStream.Length;
long contentLength = formBytes.Length + imageLength + trailingBytes.Length;
uploadRequest.ContentLength = contentLength;
// Get Request Stream
uploadRequest.AllowWriteStreamBuffering = false;
Stream strm_out = uploadRequest.GetRequestStream();
// Write to Stream
strm_out.Write(formBytes, 0, formBytes.Length);
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)imageLength))];
int bytesRead = 0;
int bytesTotal = 0;
imageMemoryStream.Seek(0, SeekOrigin.Begin);
while ((bytesRead = imageMemoryStream.Read(buffer, 0, buffer.Length)) != 0)
{
strm_out.Write(buffer, 0, bytesRead); bytesTotal += bytesRead;
}
strm_out.Write(trailingBytes, 0, trailingBytes.Length);
// Close Stream
strm_out.Close();
// Get Web Response
HttpWebResponse response = uploadRequest.GetResponse() as HttpWebResponse;
// Create Stream Reader
StreamReader reader = new StreamReader(response.GetResponseStream());
// Return
return reader.ReadToEnd();
}
You have to construct the multipart/form-data yourself using byte arrays.
Anyway I've already done this. You can check out the Facebook Graph Toolkit at http://computerbeacon.net/ . I'll update the toolkit to version 0.8 in a few days, which will include this "post photo to facebook wall" function as well as other new features and updates.
I was able to post pictures using RestSharp:
// url example: https://graph.facebook.com/you/photos?access_token=YOUR_TOKEN
request.AddFile("source", imageAsByteArray, openFileDialog1.SafeFileName, getMimeType(Path.GetExtension(openFileDialog1.FileName)));
request.addParameter("message", "your photos text here");
User API or Page API for posting photos
How to convert Image to Byte Array
Note: I was passing an empty string as the mime type and facebook was smart enough to figure it out.
Maybe useful
[TestMethod]
[DeploymentItem(#".\resources\velas_navidad.gif", #".\")]
public void Post_to_photos()
{
var ImagePath = "velas_navidad.gif";
Assert.IsTrue(File.Exists(ImagePath));
var client = new FacebookClient(AccessToken);
dynamic parameters = new ExpandoObject();
parameters.message = "Picture_Caption";
parameters.subject = "test 7979";
parameters.source = new FacebookMediaObject
{
ContentType = "image/gif",
FileName = Path.GetFileName(ImagePath)
}.SetValue(File.ReadAllBytes(ImagePath));
//// Post the image/picture to User wall
dynamic result = client.Post("me/photos", parameters);
//// Post the image/picture to the Page's Wall Photo album
//fb.Post("/368396933231381/", parameters); //368396933231381 is Album id for that page.
Thread.Sleep(15000);
client.Delete(result.id);
}
Reference:
Making Requests