今天写代码,报错:远程服务器返回错误: (500) 内部服务器错误,开始以为是服务器的问题,后来才发现是自己写请求的时候的问题,出问题之前,我的HTTP请求是这么写的:

 public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int timeout,  string param)
        {
            HttpWebRequest request = null;

            request = WebRequest.Create(url) as HttpWebRequest;
            request.Proxy = null;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            if (timeout > 0)
                request.Timeout = timeout;
            if (!string.IsNullOrEmpty(param))
                request.Headers.Add("Authorization", param);

       
            //发送POST数据  
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                        i++;
                    }
                }
                byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            string[] values = request.Headers.GetValues("Content-Type");
            return request.GetResponse() as HttpWebResponse;
        }

注意请求头:request.ContentType = “application/x-www-form-urlencoded”;

然后我换了一种请求方式:

   public static HttpWebResponse CreatePostHttpResponse(string url, string jsonParam)
        {
            HttpWebRequest request = null;

            request = WebRequest.Create(url) as HttpWebRequest;
            request.Proxy = null;
            request.Method = "POST";
            request.ContentType = "application/json";


            byte[] data = Encoding.UTF8.GetBytes(jsonParam);
            request.ContentLength = data.Length;
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            return request.GetResponse() as HttpWebResponse;
        }

注意请求头 request.ContentType = “application/json”;

总结,因为他们需要的请求头是标准的json格式,但是我发送的请求头格式不是标准的json格式,所以报这个错了,改一下就OK了,

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐