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

时间:2019-06-06 22:33:03

标签: c# jquery rest system.net.httpwebrequest jquery-ajaxq

我正在调用Rest API的Http方法是“ PUT”,我正在通过“ API-KEY”传递JSON数据。相同的API请求在jQuery Ajax调用中起作用,但在HttpWebRequest的C#中不起作用。 请查看异常消息: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);
    }
});
});

任何想法我在做什么错。

2 个答案:

答案 0 :(得分:0)

您的json数据没有花括号。 您正在发送类似:

"name": "AdithyaM",
"tin": "x",
"tinType": "U",
"checks": "DT"

何时应为:

{
    "name": "AdithyaM",
    "tin": "x",
    "tinType": "U",
    "checks": "DT"
}

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

答案 1 :(得分:0)

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

copy = cour;
cour = cour->suivant;
free(copy);