post 请求数据返回 Unsupported Media Type

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了post 请求数据返回 Unsupported Media Type相关的知识,希望对你有一定的参考价值。

出现这个“415 Unsupported Media Type” 错误的原因:

经过自己的测试,最终是没有加上“webrequest.ContentType = "application/json;charset=UTF-8";”  这句话规定请求的数据为json所导致的。

请求post的代码如下:

public static string GetPostData(string url, string paramstr)
        {
            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.Method = "post";
            webrequest.ContentType = "application/json;charset=UTF-8";

            byte[] postdatabyte = Encoding.UTF8.GetBytes(paramstr);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream;
            stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();



            using (var httpWebResponse = webrequest.GetResponse())
            using (StreamReader responseStream = new StreamReader(httpWebResponse.GetResponseStream()))
            {

                String ret = responseStream.ReadToEnd();



                return ret;
            }
        }

这样就会正常返回请求的json数据了。

以上是关于post 请求数据返回 Unsupported Media Type的主要内容,如果未能解决你的问题,请参考以下文章