【Spring MVC】REST APIにて基本的なXMLまたはPDFを返却する方法

概要

REST APIアプリにて、XML情報またはPDF情報を返却する方法についてまとめた。

あわせて読みたい

概要 これから数回にかけてREST APIについて学んだことを載せていく。 今回はREST APIの仕組みとプロジェクト作成方法について紹介する。 尚、RESTとは何かということについては取り扱わない。   仕組み[…]

 

前提

動作確認はTalend API Testerを使用した。
Talend API Testerの使用方法については以下を参照。

あわせて読みたい

概要 GUIのツールを使用してシンプルにREAT APIアプリにリクエストを送りたいと思い、Talend API Testerを使用してみた。 いろいろと便利だったため、基本的な使用方法について簡単にまとめた。   事[…]

Talend API Testerを使用してREST APIにリクエストする方法

 

基本的なXML返却

返却したいxmlファイルを参照し、バイナリ情報に変換して返却する。

 

XMLの用意

「src/main/resources/files/xml」フォルダを用意し、sample.xmlを格納した。
このファイルをコントローラーから参照する。

 

sample.xml


<?xml version="1.0" encoding="UTF-8"?>
<person>
    <name>John Doe</name>
    <address>
        <street>123 Main St</street>
        <city>Springfield</city>
        <state>IL</state>
        <postalCode>62701</postalCode>
    </address>
    <phoneNumbers>
        <phoneNumber type="home">555-1234</phoneNumber>
        <phoneNumber type="work">555-5678</phoneNumber>
    </phoneNumbers>
    <email>johndoe@example.com</email>
</person>

 

コントローラークラス

XMLのファイル名と中身の情報を返却する。

 

Rest08Controller.java


package com.example.rest_prototype.web.controller.rest08;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Rest08Controller {
	@Autowired
	private ResourceLoader resourceLoader;

	private static final String CONTENT_DISPOSITION = "Content-Disposition";
	private static final String CONTENT_TYPE = "Content-Type";
	private static final String CONTENT_TYPE_XML = "application/xml";
	/**
	 * XML情報を返却する
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@GetMapping(value = "rest08/xml")
	public ResponseEntity<byte[]> getXml() throws IOException {
		// クラスパスに配置したXML情報取得
		var xmlFile = resourceLoader.getResource("classpath:files/xml/sample.xml");
		byte[] content = FileCopyUtils.copyToByteArray(xmlFile.getInputStream());

		var headers = new HttpHeaders();
		// Content-DispositionにURLエンコードしたファイル名を設定
		String encodedFileName = URLEncoder.encode("XMLサンプル.xml", StandardCharsets.UTF_8.toString());
		headers.add(CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"");
		// コンテンツタイプにXMLを指定
		headers.add(CONTENT_TYPE, CONTENT_TYPE_XML);

		return ResponseEntity.ok().headers(headers).body(content);
	}
}

 

var xmlFile = resourceLoader.getResource(“classpath:files/xml/sample.xml”);
byte[] content = FileCopyUtils.copyToByteArray(xmlFile.getInputStream());

用意したxmlファイルを参照して、バイナリ情報に変換している。

 

var headers = new HttpHeaders();
(略)
return ResponseEntity.ok().headers(headers).body(content);

org.springframework.http.HttpHeadersを用意して任意のヘッダー情報を作成できる。
レスポンスエンティティにヘッダーとレスポンスボディ(xml情報のバイナリデータ)を設定している

 

String encodedFileName = URLEncoder.encode(“XMLサンプル.xml”, StandardCharsets.UTF_8.toString());
headers.add(CONTENT_DISPOSITION, “attachment; filename=\”” + encodedFileName + “\””);

ファイル名を設定している。
日本語などを設定する場合、文字化けしてしまうためURLエンコードしている。
URLエンコードしたファイル名は、ヘッダーの「Content-Disposition」に設定する。
これにより、リクエスト元でレスポンスのヘッダーにある「Content-Disposition」を参照してファイル名を取得できる

 

// コンテンツタイプにXMLを指定
headers.add(CONTENT_TYPE, CONTENT_TYPE_XML);

ヘッダーの「Content-Type」に「application/xml」を設定している。
これにより、レスポンスがXML形式となる。

 

動作確認

Talend API Testerを使用して動作確認を行う。

 

リクエスト


http://localhost:8080/rest_prototype/rest08/xml

 

レスポンス


<?xml version="1.0" encoding="UTF-8" ?>
<person>
    <name>John Doe</name>
    <address>
        <street>123 Main St</street>
        <city>Springfield</city>
        <state>IL</state>
        <postalCode>62701</postalCode>
    </address>
    <phoneNumbers>
        <phoneNumber type="home">555-1234</phoneNumber>
        <phoneNumber type="work">555-5678</phoneNumber>
    </phoneNumbers>
    <email>johndoe@example.com</email>
</person>

 

基本的なPDF返却

返却したいpdfファイルを参照し、バイナリ情報に変換して返却する。

 

PDFの用意

「src/main/resources/files/pdf」フォルダを用意し、sample.pdfを格納した。
このファイルをコントローラーから参照する。

 

コントローラークラス

PDFのファイル名と中身の情報を返却する。

 

Rest08Controller.java


package com.example.rest_prototype.web.controller.rest08;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Rest08Controller {
	@Autowired
	private ResourceLoader resourceLoader;

	private static final String CONTENT_DISPOSITION = "Content-Disposition";
	private static final String CONTENT_TYPE = "Content-Type";
	private static final String CONTENT_TYPE_XML = "application/xml";
	private static final String CONTENT_TYPE_PDF = "application/pdf";
	/**
	 * XML情報を返却する
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@GetMapping(value = "rest08/xml")
	public ResponseEntity<byte[]> getXml() throws IOException {
		// クラスパスに配置したXML情報取得
		var xmlFile = resourceLoader.getResource("classpath:files/xml/sample.xml");
		byte[] content = FileCopyUtils.copyToByteArray(xmlFile.getInputStream());

		var headers = new HttpHeaders();
		// Content-DispositionにURLエンコードしたファイル名を設定
		String encodedFileName = URLEncoder.encode("XMLサンプル.xml", StandardCharsets.UTF_8.toString());
		headers.add(CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"");
		// コンテンツタイプにXMLを指定
		headers.add(CONTENT_TYPE, CONTENT_TYPE_XML);

		return ResponseEntity.ok().headers(headers).body(content);
	}

	/**
	 * PDF情報を返却する
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@GetMapping(value = "rest08/pdf")
	public ResponseEntity<byte[]> get() throws IOException {
		// クラスパスに配置したPDF情報取得
		var pdfFile = resourceLoader.getResource("classpath:files/pdf/sample.pdf");
		byte[] content = FileCopyUtils.copyToByteArray(pdfFile.getInputStream());


		var headers = new HttpHeaders();
		// Content-DispositionにURLエンコードしたファイル名を設定
		String encodedFileName = URLEncoder.encode("PDFサンプル", StandardCharsets.UTF_8.toString());
		headers.add(CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"");
		// コンテンツタイプにPDFを指定
		headers.add(CONTENT_TYPE, CONTENT_TYPE_PDF);

		return ResponseEntity.ok().headers(headers).body(content);
	}
}

 

// コンテンツタイプにPDFを指定
headers.add(CONTENT_TYPE, CONTENT_TYPE_PDF);

ヘッダーの「Content-Type」に「application/pdf」を設定している。
これにより、レスポンスがPDF形式となる。
その他はXMLの補足説明と同様。

 

動作確認

Talend API Testerを使用して動作確認を行う。

 

リクエスト


http://localhost:8080/rest_prototype/rest08/pdf

レスポンスはPDFのバイナリデータとなる。
Talend API Testerの場合、そのままファイルをダウンロード可能。

 

まとめ

 

☑ XMLやPDFは、基本的にバイナリデータとして返却する

☑ 「Content-Disposition」を使用することで、ファイル名称をクライアント側に返却することができる

☑ ResponseEntityにファイル名(ヘッダー)とファイルデータ情報(ボディ)を設定して返却する

 

スポンサーリンク