Rest-API Status-Code 415: Unsupported Media Type

Tintenfisch

Bekanntes Mitglied
Hallo Forum,
Ich habe mit Spring-Boot eine kleine rest-API geschrieben, die soweit auch funktioniert. Allerdings kommt es bei POST-Methoden, bei denen ein RequestBody als Übergabetyp gefordert ist, immer zu dem Fehler Unsuported Media Type 415.
Sollte ich über Postman eine Anfrage stellen, funktioniert alles, somit tauchen die Fehler nur aus der Clientanwendung aus auf.

Ich habe mehrere Varianten ausprobiert, hier einmal mit "Spring-Boot RestTemplate" und mit einer "regulären" HttpURLConnection. Jedoch immer mit dem gleichen Fehler.

Vorab schon mal vielen Dank fürs Lesen und anbei mal der wohl relevante Code.
API:
Java:
@RestController
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @PostMapping (path = "/register", consumes = {"application/json"})
    private ResponseEntity<User> register (@RequestBody User user) {
        
        user.setApiKey(UUID.randomUUID().toString());
        var savedUser = userRepository.save(user);
        return new ResponseEntity<User> (savedUser, HttpStatus.CREATED);
    }
}

Client via Spring-Boot RestTemplate:
Java:
    private static void post () {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8080/register";
        
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_JSON);
            
        String jsonString = createJsonUser("UsernameX", "EmailX", "PasswordX").toString();
        
        HttpEntity<String> entity = new HttpEntity<String>(jsonString, headers);
        Object result = restTemplate.exchange(
                url, HttpMethod.POST, entity, Object.class);       
        System.out.println(result);
    }

Client via HttpURLConnection:
Java:
private static void register () throws IOException {
    String jsonString = createJsonUser("TestUername", "TestEmail", "TestPassword").toString();
    String urlString = "http://localhost:8080/register";
        
    URL url = new URL(urlString);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("POST");
        
    urlConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
    urlConnection.setRequestProperty("Access", "application/json");
        
    urlConnection.getOutputStream().write(jsonString.getBytes(StandardCharsets.UTF_8));
    urlConnection.getOutputStream().close();
        
    InputStream input;
    if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
        input = urlConnection.getInputStream();
    } else {
        input = urlConnection.getErrorStream();
    }
}
 

Oneixee5

Top Contributor
Zum Test würde ich "consumes" und "produces" einfach mal weglassen.
Ich denke aber das müsste so aussehen, da du ja die Header im Client explizit setzt.
Java:
@PostMapping(path = "register",
        consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
oder das weglassen
Java:
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
bzw.
urlConnection.setRequestProperty("Access", "application/json"); // hier ist bestimmt "Accept" gemeint
Json ist immer UTF-8, das ist also überflüssig.
Java:
urlConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
Hier sollte doch User verwendet werden, nicht Object:
Java:
Object result = restTemplate.exchange(
                url, HttpMethod.POST, entity, Object.class);

User result = restTemplate.exchange(
                url, HttpMethod.POST, entity, User.class);
 

mihe7

Top Contributor
Json ist immer UTF-8, das ist also überflüssig.
[Klugscheißermodus an]
Ein JSON Dokument ist immer ein Unicode-String, das Encoding ist aber nicht definiert, kann also z. B. auch UTF-16 sein, wenngleich UTF-8 das Standardencoding ist (vgl. ECMA-404 und RFC4627). Allerdings sieht das RFC für den Mediatype keinen charset-Parameter vor und das Encoding lässt sich aus den ersten Bytes ableiten.
[/Klugscheißermodus an]
 

Ähnliche Java Themen

Neue Themen


Oben