c# - 使用 HttpWebRequest 和 PUT 方法调用 Rest ful 服务
问题描述
我正在调用 Rest API Http 方法是“PUT”,我正在使用“API-KEY”传递 JSON 数据。相同的 API 请求在 jQuery Ajax 调用中有效,但在带有 HttpWebRequest 的 C# 中无效。请参阅异常消息:异常消息 我总是收到错误:
"The remote server returned as error: (400) Bad Request"
下面是 C# 代码:
StringBuilder jsonData = new StringBuilder();
jsonData.Append(@"""name"": """ + name + '"' + ",");
jsonData.Append(@"""tin"": """ + tin + '"' + ",");
jsonData.Append(@"""tinType"": ""U"",");
jsonData.Append(@"""checks"": ""DT""");
string URL = @"https://api.dev.gmc-pharmacy.com/tesmdm/dev/tesmdm/taxvalidation/";
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL);
request.Method = "PUT";
request.ContentType = "application/json";
request.ContentLength = jsonData.Length;
request.Headers.Add("GMC-API-KEY", "427b9574-27a6-4e21-8eea-c3e2a14e4ebe");
request.ProtocolVersion = HttpVersion.Version10;
byte[] postBytes = Encoding.UTF8.GetBytes(jsonData.ToString());
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result;
using (StreamReader rdr = new StreamReader(response.GetResponseStream()))
{
result = rdr.ReadToEnd();
}}
下面是 jQuery 中的工作代码:
$("#btnTINSubmit").click(function() {
var URL = "https://api.dev.gmc-pharmacy.com/tesmdm/dev/tesmdm/taxvalidation/";
var data = {
name: $("#txtSupplierName").val(), // Supplier Name
tin: $("#txtSupplierTIN").val(),
tinType: "U",
checks: "DT"
};
$.ajax({
//url: getExactPath('/Supplier/TaxValidate'),
url: URL,
type: "PUT",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader("GMC-API-KEY ", "427b9574-27a6-4e21-8eea-c3e2a14e4ebe");
},
success: function(data) {
alert(data);
$('#TINResponse').text(data.matchInfoResponse[0].matchResultResponse.message);
},
error: function(xhr, ajaxOptions, thrownError) {
$('#TINResponse').text(xhr.response);
alert(thrownError);
}
});
});
任何想法我做错了什么。
解决方案
您的 json 数据没有大括号。您发送的内容如下:
"name": "AdithyaM",
"tin": "x",
"tinType": "U",
"checks": "DT"
什么时候应该是这样的:
{
"name": "AdithyaM",
"tin": "x",
"tinType": "U",
"checks": "DT"
}
这可能是您的服务器响应错误请求响应的原因,因为它无法识别请求的主体
推荐阅读
- java - 从十六进制值获取单个字节
- sql - 根据条件从一列中提取数据并存储在另一列中
- python - 根据列条件添加具有来自另一个数据框的值的列
- bixby - 在为主题标签提供训练示例时,我应该提供数字还是字母?
- perl - 使用 Perl 恢复目录中多个 .txt 中的特定行
- r - 如何从 autoconf 脚本 configure.ac 中检查程序的版本
- javascript - 为什么 \n 有时在 javascript 中充当空格而不是换行符?
- php - 添加一个“计数器”变量以通过 PHP 在 mail() 中发送
- python - Python变点算法
- c# - 匹配除 html 标签内容之外的所有文本