2012-03-20 23 views
5

Tôi cần tải tệp ics lên API REST. Ví dụ duy nhất được đưa ra là lệnh curl..NET tương đương với curl để tải tệp lên REST API?

Lệnh sử dụng để tải lên các tập tin sử dụng curl trông như thế này:

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

Làm thế nào tôi có thể làm điều này bằng cách sử dụng HttpWebRequest trong C#?

Cũng lưu ý rằng tôi chỉ có thể có ics dưới dạng chuỗi (không phải tệp thực tế).

+0

http://stackoverflow.com/questions/2360832/using-net-to-post-a-file-to-server-httpwebrequest-or-webclient vẻ để làm một cái gì đó tương tự – dash

Trả lời

5

Tôi đã tìm được giải pháp làm việc. Quirk là đặt phương thức theo yêu cầu thành PUT thay vì POST. Dưới đây là một ví dụ về mã tôi đã sử dụng:

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(); 
Các vấn đề liên quan