Reputation: 1952
I am in the process of changing one of our API calls
The current call is in the format
[url]/[user]/[itemid]
The new call is in the format:
[url]
{
"user": ["user"],
"category": ["category"],
"itemIds": ["itemid1"], ["itemid2"]
}
In C# I currently build up the request as follows:
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();
Please can someone advise me on how to populate the new HTTP Request with the detail given above?
Any assistance, advice or links would be greatly appreciated.
Upvotes: 0
Views: 213
Reputation: 56536
You should use Json.NET as a serializer and write to the request stream. You should have a class that mirrors your data structure for your request. 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();
The request sent will be like:
{
"user": 1,
"category": 1,
"itemIds": [
"1",
"2"
]
}
Upvotes: 1