使用 HttpWebRequest 和 PUT 方法调用 Rest ful 服务

Call Rest ful service using HttpWebRequest and PUT Method

我正在调用 Rest API Http 方法是 "PUT",我正在使用 "API-KEY" 传递 JSON 数据。相同的 API 请求在 jQuery Ajax 调用中工作,但在 C# 中与 HttpWebRequest 不工作。 请查看异常消息:Exception Message 我总是出错:

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

这可能是您的服务器响应错误请求响应的原因,因为它无法识别请求的正文

我已经更正了 json 字符串格式,如下所示。现在一切都完美了。

jsonData.Append(@"{""name"": """ + name + '"' + ",");
jsonData.Append(@"""tin"": """ + tin + '"' + ",");
jsonData.Append(@"""tinType"": ""U"",");
jsonData.Append(@"""checks"": ""DT""}");