首页 > 解决方案 > 使用 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);
    }
});
});

任何想法我做错了什么。

标签: c#jqueryrestsystem.net.httpwebrequestjquery-ajaxq

解决方案


您的 json 数据没有大括号。您发送的内容如下:

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

什么时候应该是这样的:

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

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


推荐阅读