如何使用以下HTTP + JSON提供窗口服务的POST请求
我正在尝试使用Windows服务向WorkWave API发送请求。 Workwave API示例提供的代码如下所示:
POST /api/v1/territories/429defc8-5b05-4c3e-920d-0bb911a61345/orders HTTP/1.0
Accept: application/json
X-WorkWave-Key: YOUR API KEY
Host: wwrm.workwave.com
Content-Type: application/json
{
"orders": [
{
"name": "Order 6 - API",
"eligibility": {
"type": "on",
"onDates": [
"20151204"
]
},
"forceVehicleId": null,
"priority": 0,
"loads": {
"people": 2
},
"delivery": {
"location": {
"address": "2001 2nd Ave, Jasper, AL 35501, USA"
},
"timeWindows": [
{
"startSec": 43200,
"endSec": 54000
}
],
"notes": "Order added via API",
"serviceTimeSec": 1800,
"tagsIn": [],
"tagsOut": [],
"customFields": {
"my custom field": "custom field content",
"orderId": "abcd1234"
}
}
}
]
}
这是我第一次使用GET / POST请求。 所以我不确定上面会发生什么,我怎么用c#代码来做到这一点。 我需要遵循的步骤是什么,我该如何做到这一点。 感谢您的时间和代码。
你可以像下面这样使用HttpWebRequest
:
string PostJsonToGivenUrl(string url, object jsonObject)
{
string resultOfPost = string.Empty;
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.ContentType = "application/json";
httpRequest.Method = "POST";
using (StreamWriter writer = new StreamWriter(httpRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(jsonObject);
writer.Write(json);
}
HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
resultOfPost = streamReader.ReadToEnd();
}
return resultOfPost;
}
如果您需要知道如何使用JavaScriptSerializer
来形成json字符串,请查看以下链接:https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer(v = vs.110)。 ASPX
如果您需要更多关于HttpWebRequest
信息,请点击此链接:https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(v= HttpWebRequest
也检查这个答案可能会有帮助:如何发布JSON到服务器?
首先,您需要创建请求和响应对象。 你可以使用类似json2charp.com的c#类创建器。
public class Eligibility
{
public string type { get; set; }
public List<string> onDates { get; set; }
}
public class Loads
{
public int people { get; set; }
}
public class Location
{
public string address { get; set; }
}
public class TimeWindow
{
public int startSec { get; set; }
public int endSec { get; set; }
}
public class CustomFields
{
public string myCustomField { get; set; }
public string orderId { get; set; }
}
public class Delivery
{
public Location location { get; set; }
public List<TimeWindow> timeWindows { get; set; }
public string notes { get; set; }
public int serviceTimeSec { get; set; }
public List<object> tagsIn { get; set; }
public List<object> tagsOut { get; set; }
//this field will be Dictionary...
public CustomFields customFields { get; set; }
}
public class Order
{
public string name { get; set; }
public Eligibility eligibility { get; set; }
public object forceVehicleId { get; set; }
public int priority { get; set; }
public Loads loads { get; set; }
public Delivery delivery { get; set; }
}
public class OrderRequest
{
public List<Order> orders { get; set; }
}
public class OrderResponse
{
public string requestId { get; set; }
}
并用api参考示例值创建请求对象实例(C#)。
OrderRequest GetOrderRequestObject()
{
var rootObj = new OrderRequest
{
orders = new List<Order>()
};
var order = new Order
{
name = "Order 6 - API",
eligibility = new Eligibility
{
type = "on",
onDates = new List<string>() { "20151204" }
},
forceVehicleId = null,
priority = 2,
loads = new Loads
{
people = 2
},
delivery = new Delivery
{
location = new Location
{
address = "2001 2nd Ave, Jasper, AL 35501, USA"
},
timeWindows = new List<TimeWindow>(){
new TimeWindow{
startSec =43200,
endSec=54000
}},
notes = "Order added via API",
serviceTimeSec = 1800,
tagsIn = new List<object>(),
tagsOut = new List<object>(),
customFields = new CustomFields
{
myCustomField = "custom field content",
orderId = "abcd1234"
}
},
};
rootObj.orders.Add(order);
return rootObj;
}
创建一个通用的post方法..(你需要添加HttpClient引用 - NuGet)
TRSULT HttpPostRequest<TREQ, TRSULT>(string requestUrl, TREQ requestObject)
{
using (var client = new HttpClient())
{
// you should replace wiht your api key
client.DefaultRequestHeaders.Add("X-WorkWave-Key", "YOUR API KEY");
client.BaseAddress = new Uri("wrm.workwave.com");
using (var responseMessage = client.PostAsJsonAsync <TREQ>(requestUrl, requestObject).Result)
{
TRSULT result = responseMessage.Content.ReadAsAsync<TRSULT>().Result;
return result;
}
}
}
现在,你可以提出要求..
var orderReqeuest = GetOrderRequestObject();
OrderResponse orderResponse = HttpPostRequest<OrderRequest, OrderResponse>("/api/v1/territories/429defc8-5b05-4c3e-920d-0bb911a61345/orders", orderReqeuest);
更新 :
我们需要添加Microsoft ASP.NET Web API 2.2客户端库的参考
链接地址: http://www.djcxy.com/p/45889.html上一篇: How to make a POST request with window service given the following HTTP + JSON
下一篇: How to deserialize json to multiple types dynamically in c#