httpwebrequest 201创建了C#表单,如何从服务器获取所创建资源的位置

时间:2018-10-11 15:46:16

标签: c# rest httpwebrequest httpwebresponse

正如标题所述,我可以通过正文https://im-legend.test.connect.paymentsense.cloud/pac/terminals/22162152/transactions向服务器{ "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);
}

1 个答案:

答案 0 :(得分:0)

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

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

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