简体   繁体   English

POST方法JSON WebAPI请求失败,出现400错误请求

[英]Post method JSON WebAPI request fails with 400 bad request

I am new to ASP .net. 我是ASP .net的新手。 I am trying to hit a webservice. 我正在尝试打Web服务。 The request type is GET. 请求类型为GET。 Using POST method and content type is JSON. 使用POST方法和内容类型是JSON。 I have used the online code and tried running. 我已使用在线代码并尝试运行。 It always turn out to be bad request 400. 请求400总是很糟糕。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;

namespace TestSuit_Get
{
    class Program
    {
        private const string URL = "http://10.33.20.54:8111/ucpData/customer/v1/getCustomer";

        private const string DATA = @"{""header"":{ ""messageId"":""123""},""body"":{ ""requestEntity"":{""productCode"":""002"", ""customerReferenceNumber"": 4010021421 }}}";
        static void Main(string[] args)
        {
            Program.CreateObject();
        }

        private static void CreateObject()
        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = "POST";
            request.ContentType = "application/json";
           // request.ContentLength = DATA.Length;
            using (Stream webStream = request.GetRequestStream())
            using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
            {

                JavaScriptSerializer json_serializer = new JavaScriptSerializer();
                Object routes_list =
                     json_serializer.DeserializeObject(DATA);
                requestWriter.Write(routes_list);
            }

            try
            {
                WebResponse webResponse = request.GetResponse();
                using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
                using (StreamReader responseReader = new StreamReader(webStream))
                {
                    string response = responseReader.ReadToEnd();
                    Console.Out.WriteLine(response);
                }
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("-----------------");
                Console.Out.WriteLine(e.Message);
            }

        }
    }
}

Please help me in making it work. 请帮助我使它工作。 Next step would be instead passing this request manually i should be pass values dynamically with same template and get results of all GET requests. 下一步将改为手动传递此请求,我应该使用同一模板动态传递值并获取所有GET请求的结果。

Don't use the ancient HttpWebRequest , use HttpClient . 不要使用古老的HttpWebRequest ,而要使用HttpClient Also, if a web service returns unexpected responses, use a debugging tool like Fiddler to inspect what exactly you're sending and receiving. 此外,如果Web服务返回意外响应,请使用调试工具(例如Fiddler)检查您要发送和接收的内容。

In this case, your requestWriter.Write(routes_list) will literally write the string System.Object to the request stream, which isn't what you want. 在这种情况下,您的requestWriter.Write(routes_list)实际上会将字符串System.Object写入请求流,这不是您想要的。 You already have the JSON string you want to send, so why deserialize it into an object you then want to send? 您已经具有要发送的JSON字符串,那么为什么将其反序列化为您要发送的对象?

Simply send the string: 只需发送字符串:

requestWriter.Write(DATA);

And again, the code can be heavily simplified using the HttpClient . 同样,可以使用HttpClient大大简化代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 400错误的请求,通过HttpClient.PutAsync将Json提交到WebApi - 400 Bad Request submitting Json to WebApi via HttpClient.PutAsync 对服务器的Json POST请求,但服务器响应(400)错误的请求 - Json POST request to the server but server respond (400) Bad Request 对WCF REST(JSON)的POST请求-WebException(400)错误的请求 - POST request to WCF REST (json) - WebException (400) bad request 如何正确发布JSON数组以避免HTTP 400错误请求? - How to properly POST JSON array to avoid HTTP 400 Bad Request? WCF POST方法获取错误400错误请求 - WCF POST method get error 400 Bad Request WCF在Post方法中给出400错误请求的错误 - WCF is giving an error of 400 Bad Request in Post Method OneFS API POST 请求上的 400 错误请求 - 400 Bad Request on OneFS API POST request Asp.net Core 2.0 POST终结点在没有JSON有效负载的情况下可以工作,但是在有JSON有效负载的情况下失败(400错误的请求) - Asp.net core 2.0 POST endpoint works without json payload, but fails (400 Bad request) with a json payload WCF方法发布json返回错误的请求 - WCF method post json return bad request Angular 2/4 - 在 Asp Net WebApi 中调用 PUT 方法给出错误请求 (400) - Angular 2/4 - Call PUT Method in a Asp Net WebApi gives Bad Request (400)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM