Invalid Media Type received following the request

I am trying to send a POST request from my Angular client to a Spring endpoint. Here is the endpoint in my HomeController:

    @RestController()
public class HomeController {

  @PostMapping(value = "/payment/{unique_transaction_id}")
  public ResponseEntity<WpfResponse> handleWpfMessage(@PathVariable("unique_transaction_id") String unique_transaction_id,
      @RequestBody WpfPaymentsDTO transaction, HttpServletRequest request) throws Exception {

    /// .... 
    MessageProcessor messageProcessor = processors.getOrDefault(transaction.getTransaction_type(), defaultProcessor);
    return ResponseEntity.ok(messageProcessor.processMessage(merchant, contract, terminal.get(), transaction, request));
  }
}

This is my TypeScript code snippet:

save(main: MainForm, hash: string): void {
    const headers = new HttpHeaders();
    headers.append('Accept', 'application/json');
    headers.append('Content-Type', 'application/json');
    this.http.post('http://localhost:8080/some_package/payment/ckjzqtyxh5pnavbjecujhuvzaa5q8n74', JSON.stringify(main), { headers }).subscribe();
  }

However, when I run the code, I encounter the following error:

HttpErrorResponse {headers: HttpHeaders, status: 415, statusText: "Unsupported Media Type", url: "http://localhost:8080/some_package/payment/ckjzqtyxh5pnavbjecujhuvzaa5q8n74", ok: false, …}error: nullheaders: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}lazyInit: ƒ ()lazyUpdate: nullnormalizedNames: Map(0) {}__proto__: Objectmessage: "Http failure response for http://localhost:8080/some_package/payment/ckjzqtyxh5pnavbjecujhuvzaa5q8n74: 415 Unsupported Media Type"name: "HttpErrorResponse"ok: falsestatus: 415statusText: "Unsupported Media Type"url: "http://localhost:8080/some_package/payment/ckjzqtyxh5pnavbjecujhuvzaa5q8n74"__proto__: HttpResponseBase

Can anyone provide guidance on how to resolve this issue?

WpfPaymentsDTO:

public class WpfPaymentsDTO {

    private String transaction_id;

    private String transaction_type;

    private String currency;

    private Integer amount;
    .....
}

Answer №1

Specify the content type within the PostMapping like this:

@PostMapping(path = "/transaction/{unique_id}", consumes = "application/xml", produces = "application/xml")

In the above example, "application/xml" is used as an example. Feel free to use the appropriate content type for your application.

Answer №2

Make sure to verify the presence of Jackson in your Spring application and ensure it is properly configured. You can find more information on this topic in the following question:

415 Unsupported MediaType for POST request in spring application

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I encountered an issue with transactions in my Spring Boot application - despite receiving an exception, the transaction is still being committed

I am facing an issue with transaction support in my Spring Boot application. Despite getting an exception in the dodajRezerwacje() function, the records in the database are being modified. I have confirmed that all services have the @Transactional annotat ...

The alias for the computed column is not correctly connected to the TypeORM Entity

I am currently working on extracting data from a table in a MySQL database using TypeORM for my Express.js project. In order to retrieve the data, I am utilizing the QueryBuilder. This is the implementation I have: const result = await this.repository.cr ...

`How to prevent Query parameters from being lost upon reloading in Nextjs Router while maintaining a clean URL structure?`

My challenge lies in sending data via router.push to a page with dynamic room id (src/pages/editor/[roomid].tsx) in Next.js. I want the URL to stay clean so users can easily edit their username in the URL if needed. When initially loaded, router.query suc ...

Combining switch statements from various classes

Is there a way to merge switch statements from two different classes, both with the same function name, into one without manually overriding the function or copying and pasting code? Class A: protected casesHandler(): void { switch (case){ ...

Precisely outline the function type that operates on an object, makes changes to its values, and then outputs the object in TypeScript

Can anyone help me create a function that generates a new object with the same keys as the input object, but with all values set to null? Here's the existing code: function nullify(arg) { var returnObj = {} for (var key in arg) { returnObj[ ...

Adjusting the background color of the custom input range thumb when the input is disabled

I've customized the input thumb on my range slider, and I'm looking to change its color when it's disabled. I attempted adding a class to the thumb like this: input[type=range]::-webkit-slider-thumb.disabled and also tried adding the disa ...

I require the JSON data to be displayed in an array format

I am looking to convert a JSON object into a JSON array in Laravel. Currently, I am receiving JSON data in object format. $category = new Categories; return Response::json(array( 'error' => false, 'category' => $category- ...

Using Selenium and Java, run headless chrome inside a Docker container

I've been attempting to run a headless Chrome browser within a Docker container by using a Docker file, but I keep encountering crash issues whenever the Automation script is executed. I have experimented with changing the Chrome driver versions to 7 ...

Tips for running a random section of code in your program

Hi, I'm currently working on writing some data to a file. If there are 10,000 lines and in every 1,000th line I want the content to be "N/D," but in the rest I need it to be "D." The challenge here is that the occurrence of "D" should be random within ...

I encountered difficulties connecting mongoose to my local MongoDB server

Hello Everyone! Currently, I am in the process of linking my node.js project to mongodb. Initially, everything worked smoothly when I used mongodb atlas. However, when I attempted to connect it using mongodb compass, I faced some issues and nothing seemed ...

Harness the power of Angular 2 on standard shared hosting services

Starting with AngularJS 2: Installed NodeJS Downloaded the initial project Ran it on Node Everything works perfectly! But now, how can I run it in a production environment on shared hosting (without Node and not on a VPS)? How can I open it in a browse ...

What is the proper type declaration for incoming data from the backend in my TypeScript code when using axios?

In the TypeScript code snippet provided, the type for 'e' (used in the function for form submission) has been figured out. However, a question arises if this type declaration is correct. Additionally, in the catch block, the type "any" is used fo ...

What is the best way to exclude multiple properties from an object in JavaScript?

Having two methods that return Pick<T, K> and Omit<T, K> types where Omit is defined as type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>, I am facing difficulty in removing multiple properties from an object. Th ...

Tips on invoking Bootstrap's collapse function without using JQuery

We are facing a challenge with our TypeScript files as we have no access to jQuery from them. Our goal is to trigger Bootstrap's collapse method... $(object).collapse(method) but without relying on jQuery. Intended Outcome //Replicates the functio ...

Encountering difficulty with retrieving information from a shared service on Angular 6

Attempting to pass JSON data from one component to another component (like parent to child) using a service. The service has two methods: setJsonData and getJsonData. Service Class import { Injectable } from '@angular/core'; @Injectable({ pr ...

Inserting multiple rows into SQL Server from a Java application.Here are a

What is the most efficient way to insert multiple rows into a SQL Server database from Java code? I am currently inserting one row at a time, but it seems quite inefficient. Any suggestions on how to improve this process? ...

In TypeScript Next.js 14 APP, object literals are limited to declaring existing properties

I encountered an error in my typescript next.js 14 APP. I need assistance resolving this issue, which states: Object literal may only specify known properties, and 'productPackages' does not exist in type '(Without<ProductCreateInput, Pr ...

Setting attributes within an object by looping through its keys

I define an enum called REPORT_PARAMETERS: enum REPORT_PARAMETERS { DEFECT_CODE = 'DEFECT_CODE', ORGANIZATION = 'ORGANIZATION' } In addition, I have a Form interface and two objects - form and formMappers that utilize the REPOR ...

Looking to programmatically define the locale for Kendo-Ui-Datepicker element

We have integrated a locale service into our existing Angular application, which sets the locale based on a dropdown selection. This locale service is part of the angular-l10n library. After acquiring Kendo-UI for Angular, we were hoping to connect the da ...

Incorporating responsive design with React and Typescript

Trying to utilize React with TypeScript, I aim to dynamically generate components based on a field name // Storing all available components const components = { ComponentA, ComponentB, }; // Dynamically render the component based on fieldName const di ...