← Назад к вопросам

Какие Content-Type можно использовать

1.0 Junior🔥 121 комментариев
#REST API и микросервисы

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI22 мар. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

Content-Type в HTTP запросах и ответах: полный справочник

Content-Type — это HTTP заголовок, который указывает на формат и кодировку передаваемых данных. Рассмотрю все основные типы и примеры использования в Java приложениях.

Основная структура Content-Type

Content-Type: type/subtype; charset=encoding

Примеры:
Content-Type: application/json; charset=utf-8
Content-Type: text/html; charset=utf-8
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary

Основные типы Content-Type

1. application/json (JSON данные)

@RestController
@RequestMapping("/api/v1/users")
public class UserController {
    
    // Spring автоматически устанавливает Content-Type: application/json
    @PostMapping(consumes = "application/json", produces = "application/json")
    public UserResponse createUser(@RequestBody UserRequest request) {
        User user = new User(request.getName(), request.getEmail());
        return new UserResponse(user.getId(), user.getName());
    }
    
    // Получение списка в JSON
    @GetMapping(produces = "application/json")
    public List<UserResponse> getAllUsers() {
        return userService.getAllUsers();
    }
}

// Request:
// POST /api/v1/users HTTP/1.1
// Content-Type: application/json
// {"name": "John", "email": "john@example.com"}

// Response:
// HTTP/1.1 200 OK
// Content-Type: application/json
// {"id": 1, "name": "John"}

2. application/x-www-form-urlencoded (Form данные)

@RestController
public class FormController {
    
    // Обработка формы как параметры URL
    @PostMapping(consumes = "application/x-www-form-urlencoded")
    public ResponseEntity<String> submitForm(
            @RequestParam String username,
            @RequestParam String password) {
        
        userService.authenticate(username, password);
        return ResponseEntity.ok("Login successful");
    }
    
    // Или использовать @RequestBody
    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody UserLoginRequest request) {
        return ResponseEntity.ok("Logged in");
    }
}

// Request:
// POST /submit-form HTTP/1.1
// Content-Type: application/x-www-form-urlencoded
// username=john&password=secret123&rememberMe=true

// В Java:
String postData = "username=john&password=secret123";
String encoded = URLEncoder.encode(postData, "UTF-8");

3. multipart/form-data (Файлы + данные)

@RestController
@RequestMapping("/api/v1/files")
public class FileUploadController {
    
    // Загрузка файла
    @PostMapping(consumes = "multipart/form-data", produces = "application/json")
    public FileUploadResponse uploadFile(
            @RequestPart("file") MultipartFile file,
            @RequestPart("metadata") String metadata) {
        
        String filename = file.getOriginalFilename();
        byte[] bytes = file.getBytes();
        
        String fileUrl = fileService.save(filename, bytes);
        return new FileUploadResponse(fileUrl);
    }
    
    // Загрузка нескольких файлов
    @PostMapping("/multiple")
    public List<FileUploadResponse> uploadMultipleFiles(
            @RequestPart("files") List<MultipartFile> files) {
        
        return files.stream()
            .map(file -> new FileUploadResponse(fileService.save(file)))
            .collect(Collectors.toList());
    }
}

// Request:
// POST /api/v1/files HTTP/1.1
// Content-Type: multipart/form-data; boundary=----WebKitFormBoundary
// 
// ------WebKitFormBoundary
// Content-Disposition: form-data; name="file"; filename="document.pdf"
// Content-Type: application/pdf
// 
// [binary PDF data]
// ------WebKitFormBoundary
// Content-Disposition: form-data; name="metadata"
// 
// {"description": "My document"}
// ------WebKitFormBoundary--

4. text/html (HTML страницы)

@Controller
public class WebController {
    
    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("title", "Welcome");
        return "index";  // Возвращает index.html с Content-Type: text/html
    }
    
    // Явно указать Content-Type
    @GetMapping("/raw-html")
    @ResponseBody
    public ResponseEntity<String> getRawHtml() {
        String html = "<h1>Hello</h1>";
        return ResponseEntity.ok()
            .contentType(MediaType.TEXT_HTML)
            .body(html);
    }
}

// Response:
// HTTP/1.1 200 OK
// Content-Type: text/html; charset=utf-8
// <h1>Hello</h1>

5. text/plain (Простой текст)

@RestController
public class TextController {
    
    @GetMapping("/text", produces = "text/plain")
    public String getPlainText() {
        return "This is plain text\nWithout HTML formatting";
    }
}

// Response:
// HTTP/1.1 200 OK
// Content-Type: text/plain; charset=utf-8
// This is plain text
// Without HTML formatting

6. application/xml (XML данные)

@RestController
@RequestMapping("/api/v1/xml")
public class XmlController {
    
    @PostMapping(consumes = "application/xml", produces = "application/xml")
    @ResponseBody
    public UserXmlResponse createUserXml(@RequestBody UserXmlRequest request) {
        return new UserXmlResponse(request.getName(), request.getEmail());
    }
}

@XmlRootElement(name = "user")
public class UserXmlRequest {
    @XmlElement
    private String name;
    
    @XmlElement
    private String email;
    // getters/setters
}

// Request:
// POST /api/v1/xml HTTP/1.1
// Content-Type: application/xml
// <?xml version="1.0" encoding="UTF-8"?>
// <user>
//     <name>John</name>
//     <email>john@example.com</email>
// </user>

// Response:
// HTTP/1.1 200 OK
// Content-Type: application/xml; charset=utf-8
// <?xml version="1.0" encoding="UTF-8"?>
// <user>
//     <name>John</name>
//     <email>john@example.com</email>
// </user>

7. application/octet-stream (Бинарные данные)

@RestController
@RequestMapping("/api/v1/download")
public class DownloadController {
    
    // Скачивание файла
    @GetMapping("/file/{id}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable String id) {
        byte[] fileContent = fileService.getFile(id);
        
        return ResponseEntity.ok()
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .header(HttpHeaders.CONTENT_DISPOSITION, 
                   "attachment; filename=\"file.bin\"")
            .body(fileContent);
    }
    
    // Скачивание PDF
    @GetMapping("/pdf/{id}")
    public ResponseEntity<byte[]> downloadPdf(@PathVariable String id) {
        byte[] pdfContent = pdfService.generate(id);
        
        return ResponseEntity.ok()
            .contentType(MediaType.APPLICATION_PDF)
            .header(HttpHeaders.CONTENT_DISPOSITION, 
                   "attachment; filename=\"document.pdf\"")
            .body(pdfContent);
    }
}

// Response:
// HTTP/1.1 200 OK
// Content-Type: application/octet-stream
// Content-Disposition: attachment; filename="file.bin"
// [binary data]

8. application/pdf (PDF документы)

@RestController
public class PdfController {
    
    @GetMapping("/invoice/{id}", produces = "application/pdf")
    public ResponseEntity<byte[]> getPdfInvoice(@PathVariable Long id) {
        byte[] pdfBytes = invoiceService.generatePdf(id);
        
        return ResponseEntity.ok()
            .contentType(MediaType.APPLICATION_PDF)
            .body(pdfBytes);
    }
}

9. image/* (Изображения)

@RestController
@RequestMapping("/api/v1/images")
public class ImageController {
    
    @GetMapping("/{id}", produces = "image/jpeg")
    public ResponseEntity<byte[]> getImageJpeg(@PathVariable String id) {
        byte[] imageBytes = imageService.getImage(id);
        return ResponseEntity.ok()
            .contentType(MediaType.IMAGE_JPEG)
            .body(imageBytes);
    }
    
    @GetMapping("/{id}/png", produces = "image/png")
    public ResponseEntity<byte[]> getImagePng(@PathVariable String id) {
        byte[] imageBytes = imageService.getImage(id);
        return ResponseEntity.ok()
            .contentType(MediaType.IMAGE_PNG)
            .body(imageBytes);
    }
    
    @GetMapping("/{id}/svg", produces = "image/svg+xml")
    public ResponseEntity<String> getImageSvg(@PathVariable String id) {
        String svgContent = imageService.getSvg(id);
        return ResponseEntity.ok()
            .contentType(MediaType.valueOf("image/svg+xml"))
            .body(svgContent);
    }
}

10. application/json-patch+json (JSON Patch)

@RestController
@RequestMapping("/api/v1/users")
public class UserPatchController {
    
    // PATCH с JSON Patch формате (RFC 6902)
    @PatchMapping(value = "/{id}", 
                  consumes = "application/json-patch+json",
                  produces = "application/json")
    public UserResponse patchUser(
            @PathVariable Long id,
            @RequestBody JsonNode patches) {
        
        User user = userService.findById(id);
        // Применить patches к user
        return userService.update(user);
    }
}

// Request:
// PATCH /api/v1/users/1 HTTP/1.1
// Content-Type: application/json-patch+json
// [
//   { "op": "replace", "path": "/email", "value": "newemail@example.com" },
//   { "op": "add", "path": "/phone", "value": "+1234567890" }
// ]

Таблица основных Content-Types

TypeSubtypeПримерИспользование
applicationjson{"key": "value"}REST API
applicationx-www-form-urlencodedkey=value&foo=barHTML Forms
applicationxmlXML документSOAP, Config
applicationpdfPDF документФайлы
applicationoctet-streamБинарные данныеЗагрузка файлов
texthtmlHTML кодВеб-страницы
textplainПростой текстЛоги, текст
textcssCSS стилиСтилизация
textjavascriptJS кодСкрипты
imagejpegJPEG картинкаФото
imagepngPNG картинкаГрафика
imagesvg+xmlSVG векторИконки
videomp4ВидеоМультимедиа
audiompegMP3 музыкаАудио
multipartform-dataФайлы + данныеЗагрузка

Content-Type в Spring Framework

@RestController
@RequestMapping("/api/v1")
public class ContentTypeExampleController {
    
    // Способ 1: через @RequestMapping
    @RequestMapping(method = RequestMethod.POST,
                   consumes = "application/json",
                   produces = "application/json")
    public ResponseEntity<UserResponse> createUser(@RequestBody UserRequest request) {
        return ResponseEntity.ok(new UserResponse(request.getName()));
    }
    
    // Способ 2: через MediaType (более явно)
    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE,
                produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<UserResponse> createUserV2(@RequestBody UserRequest request) {
        return ResponseEntity.ok(new UserResponse(request.getName()));
    }
    
    // Способ 3: множественные Content-Type
    @PostMapping(consumes = {"application/json", "application/xml"},
                produces = {"application/json", "application/xml"})
    public ResponseEntity<UserResponse> createUserFlexible(@RequestBody UserRequest request) {
        return ResponseEntity.ok(new UserResponse(request.getName()));
    }
    
    // Способ 4: явно через HttpHeaders
    @GetMapping("/custom")
    public ResponseEntity<String> customContentType() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        return new ResponseEntity<>("Custom content", headers);
    }
}

Charset (Кодировка символов)

@RestController
public class CharsetController {
    
    // UTF-8 (по умолчанию, рекомендуется)
    @GetMapping(produces = "application/json; charset=utf-8")
    public Map<String, String> responseUtf8() {
        return Map.of("message", "Привет мир");  // Кириллица
    }
    
    // ISO-8859-1 (Latin1, устаревшее)
    @GetMapping("/latin", produces = "text/plain; charset=iso-8859-1")
    public String responseLatin1() {
        return "Héllo Wörld";  // Диакритические символы
    }
}

Практический пример: многоформатный API

@RestController
@RequestMapping("/api/v1/data")
public class MultiFormatController {
    
    @GetMapping(produces = {"application/json", "application/xml", "text/csv"})
    public ResponseEntity<?> getData(
            @RequestParam(defaultValue = "json") String format) {
        
        List<User> users = userService.getAllUsers();
        
        return switch(format.toLowerCase()) {
            case "json" -> ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(users);
            
            case "xml" -> ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_XML)
                .body(users);
            
            case "csv" -> ResponseEntity.ok()
                .contentType(MediaType.TEXT_PLAIN)
                .body(convertToCsv(users));
            
            default -> ResponseEntity.badRequest().build();
        };
    }
    
    private String convertToCsv(List<User> users) {
        return users.stream()
            .map(u -> u.getId() + "," + u.getName() + "," + u.getEmail())
            .collect(Collectors.joining("\\n"));
    }
}

Итоговая рекомендация

Используй:

  • application/json для REST API (стандарт)
  • multipart/form-data для загрузки файлов
  • application/xml для SOAP и конфигов
  • text/html для веб-страниц
  • application/pdf для документов

Избегай:

  • Неправильного Content-Type (ошибки десериализации)
  • Забывать charset=utf-8 для текстовых данных
  • Смешивать JSON и XML без причины

Content-Type — это контракт между клиентом и сервером о формате передаваемых данных. Выбирай правильный тип для каждого случая!