Search code examples
c#resthttpwebrequesthttpwebresponse

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


As the title explains, I am able to make a successful POST request to the server https://im-legend.test.connect.paymentsense.cloud/pac/terminals/22162152/transactions with the body { "transactionType": "SALE", "amount": 100,"currency": "GBP"}. However, I am unable to grab the location of the created resource.

The expected scenario is that the server will respond with { "requestId": "string","location": "string"}. I would like to grab the request ID and location information that the server returns.

I have added my code below and would really appreciate it if someone could assist me or tell me where I went wrong.

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

This section here is where I perform my POST request

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

Solution

  • I would recommend to use Newtonsoft.Json and have the JSON created for you instead of creating it yourself.

    You can do this by creating an object which hold the entity:

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

    You can then create your Transaction object for your POST. So now instead of doing:

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

    Do:

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

    Now POST the Transaction:

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

    That will convert the object to JSON for you, so you don't make a mistake writing it.

    Now when you get the data as a JSON string back from the server (Can use a similar process as above), you can now do:

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

    Read more about Newtonsoft.Json