出现 (415) 不支持的媒体类型错误

问题描述 投票:0回答:8

我要做的是我必须在给定的 URL 中发布 JSON 数据 我的 JSON 是什么样子

{
    "trip_title":"My Hotel Booking",
    "traveler_info":{
        "first_name":"Edward",
        "middle_name":"",
        "last_name":"Cullen",
        "phone":{
            "country_code":"1",
            "area_code":"425",
            "number":"6795089"
        },
        "email":"[email protected]"
    },
    "billing_info":{
        "credit_card":{
            "card_number":"47135821",
            "card_type":"Visa",
            "card_security_code":"123",
            "expiration_month":"09",
            "expiration_year":"2017"
        },
        "first_name":"Edward",
        "last_name":"Cullen",
        "billing_address":{
            "street1":"Expedia Inc",
            "street2":"108th Ave NE",
            "suite":"333",
            "city":"Bellevue",
            "state":"WA",
            "country":"USA",
            "zipcode":"98004"
        },
        "phone":{
            "country_code":"1",
            "area_code":"425",
            "number":"782"
        }
    },
    "marketing_code":""
}

还有我的功能

string message = "URL";
_body="JSON DATA";
HttpWebRequest request = HttpWebRequest.Create(message) as HttpWebRequest;
if (!string.IsNullOrEmpty(_body))
{
    request.ContentType =  "text/json";
    request.Method =  "POST";

    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        streamWriter.Write(_body);
        streamWriter.Flush();
        streamWriter.Close();
    }
}

using (HttpWebResponse webresponse = request.GetResponse() as HttpWebResponse)
{
    using (StreamReader reader = new StreamReader(webresponse.GetResponseStream()))
    {
        string response = reader.ReadToEnd();
    }
}

当我发布它时;我收到错误

“远程服务器返回错误:(415) 不支持的媒体类型。”

任何人都对此有想法;我哪里错了?

c# json http post httpwebrequest
8个回答
30
投票

试试这个:

request.ContentType =  "application/json"

9
投票

对于 WebAPI >> 如果您是

calling this POST method from fiddler
,只需在标题中添加以下行即可。

Content-Type: application/json

3
投票

正如其他人所回答的,问题出在 ContentType 上。应该是“application/json”。

这是旧 WebRequest 的示例

var parameters = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

var req = WebRequest.Create(uri);

req.Method = "POST";
req.ContentType = "application/json";

byte[] bytes = Encoding.ASCII.GetBytes(parameters);

req.ContentLength = bytes.Length;

using (var os = req.GetRequestStream())
{
    os.Write(bytes, 0, bytes.Length);

    os.Close();
}

var stream = req.GetResponse().GetResponseStream();

if (stream != null)
    using (stream)
    using (var sr = new StreamReader(stream))
    {
        return sr.ReadToEnd().Trim();
    }
return "Response was null";

1
投票

我重命名了我的项目并更新了所有命名空间以进行关联,之后我收到了完全相同的消息。 我意识到我没有更新 web.config 中的命名空间(名称和合同):

<system.serviceModel>
  <services>
    <service name="X.Y.Z.Authentication" behaviorConfiguration="ServiceBehaviour">
      <endpoint address="" binding="webHttpBinding" contract="X.Y.Z.IAuthentication" behaviorConfiguration="web" bindingConfiguration="defaultRestJsonp"></endpoint>
    </service>
  </...>
</..>

希望这对阅读本文的人有所帮助。


0
投票

我不是 100% 确定,但我想你必须将文本作为 byteArray 发送,试试这个:

req = (HttpWebRequest)HttpWebRequest.Create(uri);
        req.CookieContainer = cookieContainer;
        req.Method = "POST";
        req.ContentType = "text/json";
        byte[] byteArray2 = Encoding.ASCII.GetBytes(body);
        req.ContentLength = byteArray2.Length;
        Stream newStream = req.GetRequestStream();
        newStream.Write(byteArray2, 0, byteArray2.Length);
        newStream.Close();

0
投票

这是我为接受 json 数据的 Web API 函数创建的代码示例

string Serialized = JsonConvert.SerializeObject(jsonData);
using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    HttpContent content = new StringContent(Serialized, Encoding.Unicode, "application/json"); 
    var response = await client.PostAsync("http://localhost:1234", content);   
}

0
投票

序列化要传递的数据并对其进行编码。另外,提一下 req.ContentType = "application/json";

“马丁”代码有效。

LoginInfo obj = new LoginInfo();

obj.username = uname;
obj.password = pwd;
var parameters = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

var req = WebRequest.Create(uri);

req.Method = "POST";
req.ContentType = "application/json";

byte[] bytes = Encoding.ASCII.GetBytes(parameters);

req.ContentLength = bytes.Length;

using (var os = req.GetRequestStream())
{
    os.Write(bytes, 0, bytes.Length);

    os.Close();
}

var stream = req.GetResponse().GetResponseStream();

if (stream != null)
    using (stream)
    using (var sr = new StreamReader(stream))
    {
        return sr.ReadToEnd().Trim();
    }

0
投票

您也可以仔细重新检查目标 URL,就像我遇到此问题时的情况一样,我错误传递的 URL 发生了细微的变化。 修复 URL 简单地解决了我的这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.