httpwebrequest 201 created c# form 如何从服务器获取已创建资源的位置

httpwebrequest 201 created c# form how to grab location of created resource from server

如标题所述,我能够使用 body { "transactionType": "SALE", "amount": 100,"currency": "GBP"} 向服务器 https://im-legend.test.connect.paymentsense.cloud/pac/terminals/22162152/transactions 发出成功的 POST 请求。但是,我无法获取创建资源的位置。

预期的情况是服务器将响应 { "requestId": "string","location": "string"}。我想获取服务器 returns 的请求 ID 和位置信息。

我在下面添加了我的代码,如果有人能帮助我或告诉我我哪里出错了,我将不胜感激。

 namespace RestAPI
{
    public enum httpVerb
    {
        GET,
        POST,
        PUT,
        DELETE
    }

    class RESTAPI
    {
        public string endPoint { get; set; }
        public httpVerb httpMethod { get; set; }
        public httpVerb httpMethodSale { get; set; }
        public string userPassword { get; set; }
        public int sendAmount { get; set; }

        public string postResponse { get; }

        public RESTAPI()
        {
            endPoint = string.Empty;
            httpMethod = httpVerb.GET;
            userPassword = string.Empty;
            postResponse = string.Empty;

        }

        public string makeRequest()
        {
            string strResponseValue = string.Empty;

            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(endPoint);
            request.Method = httpMethod.ToString();
            request.ContentType = "application/json";
            request.Accept = "application/connect.v1+json";

            String username = "mokhan";
            String encoded = System.Convert
                .ToBase64String(System.Text.Encoding
                    .GetEncoding("ISO-8859-1")
                    .GetBytes(username + ":" + userPassword));

            request.Headers.Add("Authorization", "Basic " + encoded);

            if (httpMethod == httpVerb.POST)
            {
                using(var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    string json = "{\"transactionType\":\"SALE\"," +
                        "\"amount\":" + sendAmount + "," +
                        "\"currency\":\"GBP\"}";

                    streamWriter.Write(json);
                    streamWriter.Flush();
                    streamWriter.Close();
                }

                var httpResponse = (HttpWebResponse) request.GetResponse();
                using(var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                }
            }

            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse) request.GetResponse();
                using(Stream responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        using(StreamReader reader = new StreamReader(responseStream))
                        {
                            strResponseValue = reader.ReadToEnd();
                        }
                    }

                }
            }

            catch (Exception ex)
            {
                if (response.StatusCode == HttpStatusCode.Created)
                {
                    MessageBox.Show("test");
                }
            }

            finally
            {
                if (response != null)
                {
                    ((IDisposable) response).Dispose();
                }
            }
            return strResponseValue;
        }
    }
}

这里的这一部分是我执行 POST 请求的地方

private void Test_Click(object sender, EventArgs e)
{
    RESTAPI rclient = new RESTAPI();
    rclient.httpMethod = httpVerb.POST;
    rclient.sendAmount = Convert.ToInt32(amount.Text);
    rclient.endPoint = "https://" + txtBox.Text + "/pac" +
        "/terminals/" + txtBox3.Text + "/transactions";
    rclient.userPassword = txtbox2.Text;

    debugOutput("REQUEST SENT");

    string strResponse = string.Empty;

    strResponse = rclient.makeRequest();

    debugOutput(strResponse);
}

我建议使用 Newtonsoft.Json 并为您创建 JSON 而不是您自己创建。

您可以通过创建一个包含实体的对象来做到这一点:

public class Transaction
{
    public string TransactionType { get; set; }
    public decimal Amount {get; set; }
    public string Currency { get; set; }
}

然后您可以为 POST 创建 Transaction 对象。所以现在而不是做:

string json = "{\"transactionType\":\"SALE\"," + "\"amount\":" + sendAmount + "," +
                          "\"currency\":\"GBP\"}";

做:

Transaction transaction = new Transaction {
                                  TransactionType = "SALE",
                                  Amount = sendAmount,
                                  Currency = "GBP" };

现在POST交易:

streamWriter.write(JsonConvert.SerializeObject(transaction));

这将为您将对象转换为 JSON,这样您就不会写错了。

现在,当您从服务器返回 JSON string 数据时(可以使用与上述类似的过程),您现在可以:

var serializer = new JsonSerializer();

using(StreamReader reader = new StreamReader(responseStream))
using (var jsonTextReader = new JsonTextReader(sr))
{
    // strResponseValue = reader.ReadToEnd();
    strResponseValue =  serializer.Deserialize(jsonTextReader);
}

阅读更多关于 Newtonsoft.Json