欢迎来到Stone的博客
Stone
Stone

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数据了。

posted @ 2017-10-10 11:03  DrMundo  阅读(3062)  评论(0编辑  收藏  举报