[英]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.