简体   繁体   English

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

[英]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 . 我正在尝试使用Windows服务向WorkWave API发布请求。 The code provide by the workwave API example is given below : 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"
        }
      }
    }
  ]
}

This is my first time when i am using GET / POST request. 这是我第一次使用GET / POST请求时。 So i'm not sure what is going in above and how can i do this with my c# code. 所以我不确定上面会发生什么,我怎么能用我的c#代码做到这一点。 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 : 您可以使用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;
    }

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 如果您需要知道如何使用JavaScriptSerializer来形成json字符串,请查看以下链接: 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 如果您需要有关HttpWebRequest更多信息,请访问以下链接: https//msdn.microsoft.com/en-us/library/system.net.httpwebrequest(v = HttpWebRequest

also check this answer it may be helpful : How to post JSON to the server? 还检查这个答案可能会有所帮助: 如何将JSON发布到服务器?

firstly, you need create request and response object. 首先,您需要创建请求和响应对象。 you can use c# class creator like json2charp.com. 你可以使用像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; }
}

And create request object instance(C#) with api reference sample values.. 并使用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;
    }

Create an generic post method.. (you need add HttpClient reference - NuGet ) 创建一个通用的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;
            }
        }
    }

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 sory,我们需要添加Microsoft ASP.NET Web API 2.2 Client Library的参考

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM