【发布时间】:2016-06-08 17:05:08
【问题描述】:
我正在与一个 RESTful API 通信并尝试通过 c# 对象捕获响应。
我之前使用 WebRequest 和 Get 成功捕获了响应,但使用 Post 和 Streamreader 我认为我犯了一些愚蠢的错误。
如果有人可以帮助我确定我的 JavaScriptSerializer 的正确结构并且我是否正确请求信息以捕获 Json 对象,我将不胜感激?
编辑:我应该道歉 - 我收到“无效 JSON 原语:”的序列化代码错误。
public void UpdatePosition(string SessionID, int AssetID, string SerialNumber)
{
positions Positions = GeneratePositions(AssetID);
var request = (HttpWebRequest)WebRequest.Create("https://some.website.com/webservices/command/v1/Position?Session=" + SessionID + "&Serial=" + SerialNumber + "&Positions=" + Positions.Latitude + "," + Positions.Longitude + "," + Positions.SpeedKmh + "," + Positions.Course + "," + Positions.Utcdatetime + "," + Positions.IgnitionState);
request.ContentType = "application/json";
request.Method = "POST";
request.KeepAlive = false;
request.Timeout = 30000;
request.ContentLength = 0;
request.Accept = "application/json";
var response = (HttpWebResponse)request.GetResponse();
Reply2 info = new Reply2();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
JavaScriptSerializer parser = new JavaScriptSerializer();
info = parser.Deserialize<Reply2>(result);
}
return;
}
public class UpdatePostionResponse
{
public responseCode ResponseCode { get; set; }
}
public class Reply2
{
public UpdatePostionResponse response { get; set; }
}
public class responseCode
{
public string Code { get; set; }
public string Message { get; set; }
}
使用 Postman 我获得了成功,但无法正确捕获响应。 回应:
<UpdatePostionResponse xmlns="http://tempuri.org/">
<ResponseCode xmlns:a="http://schemas.datacontract.org/2004/07/Command.DataContracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:Code>UpdatePositionSuccess</a:Code>
<a:Message>Positions updated.</a:Message>
</ResponseCode>
【问题讨论】:
-
服务以 XML 而不是 json 响应,并且忽略了您的接受标头。需要进一步了解该服务才能说更多。
-
@PaulSwetz 谢谢保罗,至少它为我提供了一个追求的途径。
标签: c# json asp.net-mvc api webrequest