0

I read documentation of Salesforce Chatter REST API and started to implement code in c#. See following code:

System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
        req.Method = "POST";
        req.Headers.Add("Authorization: OAuth " + accessToken);
        req.ContentType = "application/x-www-form-urlencoded";
        string par = 
               "fileName=" + fileName +
            "&feedItemFileUpload="                
           + @"D:\\MyFiles\\NewTextDocument.txt" +                  
                     "&desc=" + desc+
                     "&text=" + text;

        byte[] byteArray = Encoding.UTF8.GetBytes(par);
        req.ContentLength = byteArray.Length;
        Stream dataStream = req.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        System.Net.WebResponse resp = req.GetResponse();

I am gettig error on response The remote server returned an error: (400) Bad Request.

If i see response of error, i got following message:

Please specify a file to upload. Type in the path to the file, or use the \"Browse\" button to locate it in your local filesystem.

I have already defined the file path and name. I tried with and without @ sign before path string but getting same error. Let me know if anything is missing.

jeha
  • 10,562
  • 5
  • 50
  • 69
Brij
  • 6,086
  • 9
  • 41
  • 69

1 Answers1

2

You can easily use Fiddler to see what's going on.

You are posting a simple form where fileName and feedItemFileUpload are just like desc and text, in other words, plain simple text!

What you need to do is send the file as a stream.

I can see that you're using Hanselman's code, but that's only for text parameters

for more information on using it for files, see this answer

Upload files with HTTPWebrequest (multipart/form-data)

Community
  • 1
  • 1
balexandre
  • 73,608
  • 45
  • 233
  • 342
  • I passed file contents but still getting same error...http://www.salesforce.com/us/developer/docs/chatterapipre/salesforce_chatter_rest_api.pdf – Brij Sep 08 '11 at 07:22
  • from page 37 of that document it specifies that you need to use **JSON** or **XML**, **plus** they specify that you need to use `multipart/form-data` and in your example you are using `application/x-www-form-urlencoded`... you're not using either! As I can see, you're not very familiar with consuming Services, I would recommend that you ask help from Sales Force as you are probably a paid costumer / developer. – balexandre Sep 08 '11 at 07:30
  • I have to convert following Java code to c# https://github.com/developerforce/Chatter-REST-API/wiki/Posting-a-file-from-Java – Brij Sep 08 '11 at 08:58
  • Then create a new question an ask that question directly, be nice how to ask or it will be closed for sure if you simply say "can you guys help me converting this into c#"... – balexandre Sep 08 '11 at 09:54