简体   繁体   English

如何为RestRequest设置Content-Type标头?

[英]How to set the Content-Type header for a RestRequest?

I have a web service in a RESTful web server (java) which consumes media of type MULTIPART_FORM_DATA and produces APPLICATION_JSON . 我在RESTful Web服务器(java)中有一个Web服务,该服务器使用MULTIPART_FORM_DATA类型的媒体并产生APPLICATION_JSON I'm working on a REST client (C#) and using this web service. 我正在使用REST客户端(C#),并使用此Web服务。 I'm using RestSharp as the REST client. 我正在使用RestSharp作为REST客户端。 My code goes as follows: 我的代码如下:

RestRequest request = new RestRequest("addDelivery", Method.POST);

request.AddParameter("sessionId", this.sessionId);
request.AddParameter("deliveryTo", DeliveryTo);
request.AddParameter("deliveryName", DeliveryName);

if (fileList.Count() > 0) // If fileList is not empty
{
    // Adds all the files to request
    foreach (MyFile myFile in fileList)
    {
        request.AddFile(myFile.fileName, myFile.filePath);
    }
}

It works fine as long as I provide a file(s). 只要我提供文件,它就可以正常工作。 If a file isn't provided ( fileList is empty) I'm getting HTTP Status 415 - Unsupported Media Type . 如果未提供文件( fileList为空),我将获得HTTP状态415-不支持的媒体类型 I think as I'm not providing any file the Content-Type is automatically changed to some type other than multipart/form-data . 我认为由于我不提供任何文件,因此Content-Type会自动更改为multipart/form-data以外的其他类型。 But the web service consumes MULTIPART_FORM_DATA and maybe that's why getting this error. 但是Web服务消耗了MULTIPART_FORM_DATA ,也许这就是为什么出现此错误的原因。 I've tried adding the following code segment but getting the same error: 我尝试添加以下代码段,但得到相同的错误:

request.AddHeader("Content-Type", "multipart/form-data");

Note that this action(sending request without files) can be performed successfully from other clients (java, ios) 请注意,此操作(不带文件的发送请求)可以从其他客户端(java,ios)成功执行

我想你想要这个

request.AlwaysMultipartFormData = true

Since RestSharp has assumed Content-Type application/x-www.form-urlencode when you don't add any files you need to apply that yourself. 由于RestSharp在您不添加任何文件时都假定使用Content-Type application / x-www.form-urlencode,因此您需要自己应用该文件。 This should solve your problem. 这应该可以解决您的问题。

RestRequest request = new RestRequest("addDelivery", Method.POST);

request.AddParameter("sessionId", this.sessionId);
request.AddParameter("deliveryTo", DeliveryTo);
request.AddParameter("deliveryName", DeliveryName);

if (fileList.Count() > 0) // If fileList is not empty
{
    // Adds all the files to request
    foreach (MyFile myFile in fileList)
    {
        request.AddFile(myFile.fileName, myFile.filePath);
    }
}
else // fileList.Count() is 0 or fileList is null
{
    request.AddHeader("Content-Type", "multipart/form-data");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM