0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

postman モックサーバーの作り方

Last updated at Posted at 2025-04-29

image.png

モックサーバー作成手順

こちらを参照

外部API呼び出しもと

@Service
public class CompanyService {

    private final HttpClient client = HttpClient.newHttpClient();
    private final ObjectMapper objectMapper;

    public CompanyService() {
        this.objectMapper = new ObjectMapper()
            // ↓ JSONに、Javaクラスに存在しないフィールドがあってもエラーにしない
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
    * 外部API呼び出し
    */
    public CompanyReference dummyAPI() {
        // リクエスト設定
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(GET_EXTERNAL_URI))
                .header("Accept", "application/json")
                .build();
        
        try {
            // レスポンス.bodyを文字列形式で受け取る
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            // CompanyReferenceクラスにデシリアライズする
            return objectMapper.readValue(response.body(), CompanyReference.class);
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException("Failed to call dummy API", e);
        }
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?