httpwebrequest 201 created c#表单如何从服务器抓取已创建资源的位置
httpwebrequest 201 created c#表单如何从服务器抓取已创建资源的位置
如标题所述,我能够成功向服务器发送POST请求,服务器地址为https://im-legend.test.connect.paymentsense.cloud/pac/terminals/22162152/transactions
,请求体为{ "transactionType": "SALE", "amount": 100,"currency": "GBP"}
。然而,我无法获取创建资源的位置信息。
预期的情况是服务器将以{ "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); }
问题的出现原因是:原来的代码中使用字符串拼接的方式创建了一个JSON对象,容易出现错误。解决方法是使用Newtonsoft.Json库来创建和解析JSON对象,可以避免手动拼接字符串的错误。
解决方法如下:
1. 使用Newtonsoft.Json库,创建一个Transaction类,该类包含了需要发送的实体的属性。
2. 创建Transaction对象,并设置其属性值。
3. 将Transaction对象序列化为JSON字符串。
4. 将JSON字符串发送到服务器。
5. 当从服务器返回的数据为JSON字符串时,使用Newtonsoft.Json库将其反序列化为对象。
具体代码如下:
// 引入Newtonsoft.Json库 using Newtonsoft.Json; // 创建Transaction类 public class Transaction { public string TransactionType { get; set; } public decimal Amount {get; set; } public string Currency { get; set; } } // 创建Transaction对象 Transaction transaction = new Transaction { TransactionType = "SALE", Amount = sendAmount, Currency = "GBP" }; // 序列化Transaction对象为JSON字符串 string json = JsonConvert.SerializeObject(transaction); // 发送JSON字符串到服务器 streamWriter.write(json); // 从服务器返回的数据为JSON字符串时,反序列化为对象 var serializer = new JsonSerializer(); using(StreamReader reader = new StreamReader(responseStream)) using (var jsonTextReader = new JsonTextReader(sr)) { strResponseValue = serializer.Deserialize(jsonTextReader); }
通过使用Newtonsoft.Json库,我们可以更方便地创建和解析JSON对象,避免了手动拼接字符串时可能出现的错误。