如何设置RestRequest的Content-Type头? [英] How to set the Content-Type header for a RestRequest?

查看:5465
本文介绍了如何设置RestRequest的Content-Type头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在RESTful Web服务器(java)中有一个Web服务,它使用 MULTIPART_FORM_DATA 类型的媒体,并生成 APPLICATION_JSON 。我正在使用一个REST客户端(C#)并使用这个Web服务。我使用RestSharp作为REST客户端。我的代码如下:

I have a web service in a RESTful web server (java) which consumes media of type MULTIPART_FORM_DATA and produces APPLICATION_JSON. I'm working on a REST client (C#) and using this web service. I'm using RestSharp as the REST client. 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);
    }
}

只要我提供一个文件s)。如果没有提供文件( fileList 为空),我会收到 HTTP状态415 - 不支持的媒体类型。我认为由于我不提供任何文件 Content-Type 自动更改为除了 multipart / form-data 。但网络服务消耗 MULTIPART_FORM_DATA ,也许这就是获取此错误的原因。我试过添加以下代码段,但得到相同的错误:

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. I think as I'm not providing any file the Content-Type is automatically changed to some type other than multipart/form-data. But the web service consumes MULTIPART_FORM_DATA and maybe that's why getting this error. 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)

推荐答案

我想你想要

request.AlwaysMultipartFormData = true

这篇关于如何设置RestRequest的Content-Type头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆