0

请为我提供一些解决此错误消息的想法:

异常抛出错误请求 400

代码:

public static T MakeRequestPost<T>(string requestUrl)
{
    try
    {
        string postContent = requestUrl.Substring(requestUrl.IndexOf('?') + 1);
        string url = requestUrl.Substring(0, requestUrl.IndexOf('?'));

        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        request.Method = "POST";
        request.ContentLength = postContent.Length;
        request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";

        using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
        {
            writer.Write(postContent, 0, postContent.Length);
        }

        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            if (response.StatusCode != HttpStatusCode.OK)
                throw new Exception(String.Format(
                   "Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription));

            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));
            object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
            T jsonResponse = (T)objResponse;
            return jsonResponse;
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        return default(T);
    }
}
4

0 回答 0