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?

RestTemplateを使ってWebAPIを呼ぶ(Maven)

Last updated at Posted at 2023-07-23

Mavenプロジェクトにおいて、httpリクエストを送る。
httpクライアントとしては、springframeworkの1モジュールであるRestTemplateを使いたい。

pomに下記を追加。

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.3.13</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.15.2</version>
    </dependency>

※jackson-databindがないと、実行時、
org.springframework.web.client.RestClientException: No HttpMessageConverter for CallWebApi$1 and content type "application/json"
というエラーになる。Content-Typeがapplication/jsonでなければおそらく不要。

Javaの実装。

import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.peechan.dto.RestMessage;

public class CallWebApi {

    static RestTemplate restTemplate = new RestTemplate();
 
    public void callWebApiSample(){

        System.out.println("callWebApiSample開始");

        try{
            String url = "http://127.0.0.1:10000/spring/aaa";

            RestMessage restMessage = new RestMessage(){{
                setAaa("aaa");
            }};

            RequestEntity<RestMessage> req = 
                RequestEntity.post(url).contentType(MediaType.APPLICATION_JSON).body(restMessage);

            ResponseEntity<Long> result = restTemplate.postForEntity(url, req, Long.class);
            System.out.println(result.getStatusCode());
            System.out.println(result.getBody());
            
            System.out.println("callWebApiSample終わり");
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

実行結果

※とりあえずレスポンスボディは1固定値。

callWebApiSample開始
200 OK
1
callWebApiSample終わり
0
0
1

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?