c# - 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);
}
解决方案
我建议使用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);
}
推荐阅读
- reactjs - 生命周期方法在反应 js 中被执行两次
- functional-programming - 提取变量名
- forms - 如何阻止用户更改表单的大小
- python-3.x - 将 isalpha 应用于列表
- python-3.x - 如何在python中将多个文件存储在一个文件中?
- mysql - MySQL - 三个实体之间的多对多关系
- python - 使用 dic 从键中提取特定值
- python - 用 Python 合并 csv 文件
- python - 使用 PyCharm 调试 Python 时跳过行
- reactjs - Laravel ReactJS - 将 CSS 文件导入组件后无限编译