如何在给定以下HTTP + JSON的情况下使用窗口服务发出POST请求

时间:2017-02-13 06:22:48

标签: c# json rest 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#代码做到这一点。我需要遵循的步骤是什么,我该怎么做。感谢您的时间和代码。

2 个答案:

答案 0 :(得分:0)

您可以使用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=vs.110).aspx

同时查看此答案可能会有所帮助:How to post JSON to the server?

答案 1 :(得分:0)

首先,您需要创建请求和响应对象。你可以使用像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);

更新:

sory,我们需要添加Microsoft ASP.NET Web API 2.2客户端库的参考

enter image description here