Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET equivalent of curl to upload a file to REST API?

I need to upload an ics file to a REST API. The only example given is a curl command.

The command used to upload the file using curl looks like this:

curl --user {username}:{password} --upload-file /tmp/myappointments.ics http://localhost:7070/home/john.doe/calendar?fmt=ics

How can I do this using a HttpWebRequest in C# ?

Also note that I may only have the ics as a string (not the actual file).

like image 776
startupsmith Avatar asked Mar 20 '12 09:03

startupsmith


People also ask

How do I send a file to REST API?

To attach a file, you must include it with the Body as form-data. Once you are in the Body → form-data fields, you must enter a KEY . This should be “file” or whichever value you specified in the @RequestPart(“[value]”) . After doing so, a dropdown will appear that gives you the option of Text or File.

Can curl upload files?

Uploading files using CURL is pretty straightforward once you've installed it. Several protocols allow CURL file upload including: FILE, FTP, FTPS, HTTP, HTTPS, IMAP, IMAPS, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, and TFTP. Each of these protocols works with CURL differently for uploading data.

Can we upload file using REST API?

You can use this parameter to set metadata values to a collection already assigned to any parent folder. The rules are the same as those applied to the set metadata values REST API. Use Content-Type: application/json to describe this information as a JSON object. File to upload.

How do I upload files using curl?

How to send a file using Curl? To upload a file, use the -d command-line option and begin data with the @ symbol. If you start the data with @, the rest should be the file's name from which Curl will read the data and send it to the server. Curl will use the file extension to send the correct MIME data type.


1 Answers

I managed to get a working solution. The quirk was to set the method on the request to PUT instead of POST. Here is an example of the code I used:

var strICS = "text file content";

byte[] data = Encoding.UTF8.GetBytes (strICS);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create ("http://someurl.com");
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential ("username", "password");;
request.Method = "PUT";
request.ContentType = "text/calendar";
request.ContentLength = data.Length;

using (Stream stream = request.GetRequestStream ()) {
    stream.Write (data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse ();
response.Close ();
like image 163
startupsmith Avatar answered Oct 23 '22 03:10

startupsmith