HTTP POST 请求在 Postman 中有效,但在代码中无效

Posted

技术标签:

【中文标题】HTTP POST 请求在 Postman 中有效,但在代码中无效【英文标题】:HTTP POST request works in Postman but doesn't work in code 【发布时间】:2018-12-02 08:28:36 【问题描述】:

有一个外部 API,我必须向它发布一些对象以获取一些数据。

我在 Postman 中尝试过,效果很好,如下所示:

我也在用 C# 编写的 ASP.NET MVC 应用程序中进行了尝试:

public class TestingController : SurfaceController

    [System.Web.Http.HttpGet]
    public async System.Threading.Tasks.Task<ActionResult> Hit()
    
        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        Order order = new Order();
        ClientDetailsModel ClientDetails = new ClientDetailsModel();
        ProductDetailsModel ProductDetails = new ProductDetailsModel();
        ShippingAdressModel ShippingAdress = new ShippingAdressModel();

        ClientDetails.ClientName = "x";
        ClientDetails.Email = "x";
        ClientDetails.Note = "x";
        ClientDetails.Tel = "x";

        ProductDetails.ColorID = "1";
        ProductDetails.Quantity = "1";
        ProductDetails.SizeID = "1";
        ProductDetails.ProductMatrixRecordID = "1";

        ShippingAdress.City = "x";
        ShippingAdress.CountryID = "1";
        ShippingAdress.PostalAddress = "x";
        ShippingAdress.Street = "x";
        ShippingAdress.StreetAddress = "x";

        order.ResponseType = "JSON";
        order.Token = "P74kXRjM4W44l9qNw8u3";
        order.PaymentMode = "1";
        order.ProductDetails = ProductDetails;
        order.ShippingAddress = ShippingAdress;
        order.ClientDetails = ClientDetails;
        order.CurrencyAbbreviation = "JOD";

        var response = await client.PostAsJsonAsync<Order>("https://bmswebservices.itmam.com/OrderingManagement/Orders.asmx/PlaceOrder", order);
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

        if (!response.IsSuccessStatusCode)
        
            Console.WriteLine("ERROR:  Products Not Posted." + response.ReasonPhrase);
            return null;
        

        var cs = await response.Content.ReadAsAsync<Order>();

        return Json(cs); 
    

我收到 HTTP 500 内部服务器错误:

注意:我对其他 API 使用了相同的方式,但不同之处在于将整个对象发送到服务器。

任何人都可以帮助如何将对象应用到内容类型为application/x-www-form-urlencoded的服务器?

【问题讨论】:

在 Postman 中,您使用的是 HttpPost 方法,但 C# 代码中使用的是 HttpGet。这是为什么呢? 即使在HttpPost同样的问题,也得到了,只是为了在浏览器上测试它 【参考方案1】:

在邮递员图像中,您正在发布表单数据并获得 json 响应。

在您调用PostAsJsonAsync 的c# 代码中,它将发送JSON 内容类型。

使用FormUrlEncodedContent 并用要发送的数据填充它。

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

//...code omitted for brevity

var order = new Dictionary<string, string>();

order["ResponseType"] = "JSON";
order["Token"] = "P74kXRjM4W44l9qNw8u3";
order["PaymentMode"] = "1";
order["ProductDetails"] = JsonConvert.SerializeObject(ProductDetails);
order["ShippingAddress"] = JsonConvert.SerializeObject(ShippingAdress);
order["ClientDetails"] = JsonConvert.SerializeObject(ClientDetails);
order["CurrencyAbbreviation"] = "JOD";

var content = new FormUrlEncodedContent(order);

var url = "https://bmswebservices.itmam.com/OrderingManagement/Orders.asmx/PlaceOrder";
var response = await client.PostAsync(url, content);    
if (!response.IsSuccessStatusCode) 
    Console.WriteLine("ERROR:  Products Not Posted." + response.ReasonPhrase);
    return null;


var cs = await response.Content.ReadAsAsync<Order>();

return Json(cs); 

【讨论】:

【参考方案2】:

我的答案是

     [System.Web.Http.HttpPost]
    public ActionResult PlaceOrder(ClientDetailsModel ClientDetails, List<ProductDetailsModel> ProductDetails, ShippingAddressModel ShippingAddress, string PaymentMode, string CurrencyAbbreviation,string OrderPageURL)
    
        HttpClient client = new HttpClient();
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        var systemToken = Session["SysToken"].ToString();
        var url = Session["DomainURL"]+"/OrderingManagement/Orders.asmx/PlaceOrder";
        var parameters = "ResponseType=JSON";
        parameters += "&Token=" + systemToken;
        parameters += "&PaymentMode=" + PaymentMode;
        parameters += "&ProductDetails=" + JsonConvert.SerializeObject(ProductDetails);
        parameters += "&ShippingAddress=" + JsonConvert.SerializeObject(ShippingAddress);
        parameters += "&ClientDetails=" + JsonConvert.SerializeObject(ClientDetails);
        parameters += "&CurrencyAbbreviation=" + CurrencyAbbreviation;
        parameters += "&OrderPageURL="+ websiteDomain+"/en/order-details/?comingfrom=email";
        var response = Functions.PostRequest(url, parameters);
        var res = JsonConvert.DeserializeObject(response);
        Session["OrderNo"] = res.No;
        Session["AuthenticationCode"] = res.AuthenticationCode;
        return Json(response);
    

以及发出请求的方法:

    static public dynamic PostRequest(string apilink, string parameters)
    
        WebRequest request = WebRequest.Create(apilink);
        // Set the Method property of the request to POST.
        request.Method = "POST";
        // Create POST data and convert it to a byte array.
        string postData = parameters;
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";
        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;
        // Get the request stream.
        Stream dataStream = request.GetRequestStream();
        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.
        dataStream.Close();
        // Get the response.

        WebResponse response = request.GetResponse();


        // Display the status.

        // Get the stream containing content returned by the server.
        dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
        // Display the content.

        // Clean up the streams.
        //  var decodedJsonString = Json.Decode(responseFromServer);

        // return decodedJsonString; 
        return responseFromServer;

    

【讨论】:

以上是关于HTTP POST 请求在 Postman 中有效,但在代码中无效的主要内容,如果未能解决你的问题,请参考以下文章

postman post请求 header 和body怎么用

POST 请求在 Postman 中有效,但在 Python 请求中无效(200 响应机器人检测)

简单的 POST 请求在 Postman 中有效,但在浏览器中无效

MAXIMO API 7.6.1 POST 以编程方式创建服务请求创建空记录,但在 POSTMAN 中同样有效

postman模拟http请求

HTTP 请求在 Postman 中有效,但在 C# 代码中无效