简体   繁体   English

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

[英]HTTP POST request works in Postman but doesn't work in code

There's an external API, and I have to post some objects to it to get some data. 有一个外部API,我必须向其中发布一些对象以获取一些数据。

I tried it in Postman, and it works fine as you see below: 我在Postman中进行了尝试,如下所示,效果很好:

在此处输入图片说明

And I tried it in my ASP.NET MVC application written in C# as well: 我也在用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); 
    }
}

I got HTTP 500 internal server error: 我收到HTTP 500内部服务器错误:

在此处输入图片说明

Note: I used the same way for another APIs but the difference in for this one is sending entire objects to the server. 注意:我对另一种API使用了相同的方法,但这种方法的区别在于将整个对象发送到服务器。

Anyone can help in how to apply objects to server with the content-type application/x-www-form-urlencoded ? 任何人都可以通过内容类型application/x-www-form-urlencoded帮助如何将对象应用于服务器?

In postman image you are posting form data and getting json response. 在邮递员图像中,您正在发布表单数据并获取json响应。

In the c# code you call PostAsJsonAsync which will send JSON content type. 在C#代码中,您调用PostAsJsonAsync ,它将发送JSON内容类型。

Use FormUrlEncodedContent and populate it with the data to send. 使用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); 

the solution of my answer was 我的答案是

     [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);
    }

and the method that does the post request : 以及执行发布请求的方法:

    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;

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 HTTP请求在邮递员中有效,但在代码中不起作用 - HTTP Request works in postman but doesn't work in code laravel Passport:为什么相同的代码可用于Http Get请求,但不适用于POST? - laravel passport: why the same code works with Http Get request but doesn't work with POST? HTTP 请求在 Postman 中有效,但在 C# 代码中无效 - HTTP Request works in Postman, but not in C# code 休息客户端发布请求适用于邮递员,但不适用于 C# 代码 - Rest client post request works in postman but not in c# code HttpClient PostAsync() 不起作用,而 POSTMAN 工作正常 - HttpClient PostAsync() doesn't work while POSTMAN works fine .NET中的HTTP POST不起作用 - HTTP POST in .NET doesn't work Http post 在 Postman 中有效,但在带有 HttpClient 的 C# 中无效 - Http post works in Postman but not in C# with HttpClient c# asp .net core HTTP POST 请求适用于 Postman,但不适用于我的 Angular 客户端(404 错误) - c# asp .net core HTTP POST Request works with Postman but not with my angular client(404 error) HTTP请求(POST)在DLL库中无法正常工作? - HTTP Requests (POST) doesn't works correctly in a DLL Library? 对 https://oauth2.googleapis.com/token 的发布请求在代码中一直失败,适用于 Postman - Post Request to https://oauth2.googleapis.com/token keeps failing in Code, Works on Postman
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM