首页 > 解决方案 > httpwebrequest 201 创建 c# 表单如何从服务器获取创建资源的位置

问题描述

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

预期的情况是服务器将响应{ "requestId": "string","location": "string"}. 我想获取服务器返回的请求 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);
}

标签: c#resthttpwebrequesthttpwebresponse

解决方案


我建议使用Newtonsoft.JsonJSON为您创建,而不是自己创建。

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

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

然后,您可以Transaction为您的POST. 所以现在不要这样做:

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的更多信息


推荐阅读