使用RestSharp上传没有Multipart / Form-Data的文件

时间:2016-02-18 10:19:08

标签: restsharp

下面是一个使用标准HttpWebRequest和HttpWebResponse完成的POST请求。基本上它会发布带有一些参数的binanry文件。

如何使用RestSharp做同样的事情?

来源:

https://github.com/attdevsupport/ATT_APIPlatform_SampleApps/tree/master/RESTFul/SpeechCustom,ATT_APIPlatform_SampleApps / RESTFul / Speech / Csharp / app1 /]

HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(string.Empty+parEndPoint );

httpRequest.Headers.Add("Authorization", "Bearer " + parAccessToken);
httpRequest.Headers.Add("X-SpeechContext", parXspeechContext);
if (!string.IsNullOrEmpty(parXArgs))
{
    httpRequest.Headers.Add("X-Arg", parXArgs);
}
string contentType = this.MapContentTypeFromExtension(Path.GetExtension(parSpeechFilePath));
httpRequest.ContentLength = binaryData.Length;
httpRequest.ContentType = contentType;
httpRequest.Accept = "application/json";
httpRequest.Method = "POST";
httpRequest.KeepAlive = true;
httpRequest.SendChunked = parChunked;
postStream = httpRequest.GetRequestStream();
postStream.Write(binaryData, 0, binaryData.Length);
postStream.Close();

HttpWebResponse speechResponse = (HttpWebResponse)httpRequest.GetResponse();

1 个答案:

答案 0 :(得分:8)

一个简单的上传示例:

    RestClient restClient = new RestClient("http://stackoverflow.com/");
    RestRequest restRequest = new RestRequest("/images");
    restRequest.RequestFormat = DataFormat.Json;
    restRequest.Method = Method.POST;
    restRequest.AddHeader("Authorization", "Authorization");
    restRequest.AddHeader("Content-Type", "multipart/form-data");
    restRequest.AddFile("content", imageFullPath);
    var response = restClient.Execute(restRequest);