How to make a POST request with window service given the following HTTP + JSON

i am trying to make post request with windows service to WorkWave API . The code provide by the workwave API example is given below :

    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"
        }
      }
    }
  ]
}

This is my first time when i am using GET / POST request. So i'm not sure what is going in above and how can i do this with my c# code. What will the step i need to follow and how can i do this. Thanks for your time and for your code.


You can use HttpWebRequest like the following :

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;
    }

If you need to Know how to use JavaScriptSerializer to form json string check this link : https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer(v=vs.110).aspx

If you need more info about HttpWebRequest check this link : https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(v=vs.110).aspx

also check this answer it may be helpful : How to post JSON to the server?


firstly, you need create request and response object. you can use c# class creator like json2charp.com.

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; }
}

And create request object instance(C#) with api reference sample values..

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;
    }

Create an generic post method.. (you need add HttpClient reference - 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;
            }
        }
    }

Now, You can make request..

var orderReqeuest = GetOrderRequestObject();
OrderResponse orderResponse = HttpPostRequest<OrderRequest, OrderResponse>("/api/v1/territories/429defc8-5b05-4c3e-920d-0bb911a61345/orders", orderReqeuest);

UPDATED :

sory, we need add reference of Microsoft ASP.NET Web API 2.2 Client Library

在这里输入图像描述

链接地址: http://www.djcxy.com/p/45890.html

上一篇: .Net C#:从HttpWebResponse阅读附件

下一篇: 如何使用以下HTTP + JSON提供窗口服务的POST请求