我正在更改我们的一个API调用
当前通话的格式为
[url]/[user]/[itemid]
新通话的格式为:
[url]
{
"user": ["user"],
"category": ["category"],
"itemIds": ["itemid1"], ["itemid2"]
}
在C#中,我目前按如下方式构建请求:
string requestUrl = string.Format(_url, _userID, _itemID);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
string password = GetSignatureHash();
request.Method = "GET";
request.ContentType = "application/json";
request.Accept = "application/json";
request.Headers["Authorization"] = "Basic " + password;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
有人可以告诉我如何使用上面给出的详细信息填充新的HTTP请求吗?
非常感谢任何帮助,建议或链接。
答案 0 :(得分:1)
您应该使用Json.NET作为序列化程序并写入request stream。您应该有一个镜像您的请求的数据结构的类。 E.g。
public class MyRequest
{
[JsonProperty("user")]
public int User { get; set; }
[JsonProperty("category")]
public int Category { get; set; }
[JsonProperty("itemIds")]
public IList<string> ItemIds { get; set; }
}
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(_url);
string password = GetSignatureHash();
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "application/json";
request.Headers["Authorization"] = "Basic " + password;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
var myRequest = new MyRequest { User = 1, Category = 1,
ItemIds = new[] { "1", "2" } };
streamWriter.Write(JsonConvert.SerializeObject(myRequest));
streamWriter.Flush();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
发送的请求将如下:
{
"user": 1,
"category": 1,
"itemIds": [
"1",
"2"
]
}