![](/img/trans.png)
[英]400 Bad Request submitting Json to WebApi via HttpClient.PutAsync
[英]Post method JSON WebAPI request fails with 400 bad request
我是ASP .net的新手。 我正在尝试打Web服务。 请求类型为GET。 使用POST方法和内容类型是JSON。 我已使用在线代码并尝试运行。 请求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);
}
}
}
}
请帮助我使它工作。 下一步将改为手动传递此请求,我应该使用同一模板动态传递值并获取所有GET请求的结果。
不要使用古老的HttpWebRequest
,而要使用HttpClient
。 此外,如果Web服务返回意外响应,请使用调试工具(例如Fiddler)检查您要发送和接收的内容。
在这种情况下,您的requestWriter.Write(routes_list)
实际上会将字符串System.Object
写入请求流,这不是您想要的。 您已经具有要发送的JSON字符串,那么为什么将其反序列化为您要发送的对象?
只需发送字符串:
requestWriter.Write(DATA);
同样,可以使用HttpClient大大简化代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.