Skip to content

Instantly share code, notes, and snippets.

@sugaryo
Last active November 20, 2019 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sugaryo/18653b1bb84bad2d1a1e59f0a68b89c3 to your computer and use it in GitHub Desktop.
Save sugaryo/18653b1bb84bad2d1a1e59f0a68b89c3 to your computer and use it in GitHub Desktop.
SpringBootのRestTemplateをラップしたRestClient部品実装(PATCH対応版)
<dependency>
<!-- HttpComponentsClientHttpRequestFactoryを使用するのに必要 -->
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
import java.io.IOException;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
public class QuietlyHandler extends DefaultResponseErrorHandler {
/*
* (non-Javadoc)
*
* @see org.springframework.web.client.DefaultResponseErrorHandler#handleError(org.springframework.http.client.ClientHttpResponse)
*/
@Override
public void handleError( ClientHttpResponse response ) throws IOException {
// ■何もしない■
// デフォルト実装では HTTPステータスの 300/400系 で例外スローしているが、
// NOPでオーバーライドすることで 300/400系 でも正常ルートに乗るようにする。
// ・300系:HttpClientErrorException
// ・400系:HttpServerErrorException
}
}
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
// QuietlyHandler を使用した HttpClient 実装。
// QuietlyHandler はこのクラスの static inner class として実装して良いが、Gistでは説明の都合上javaを分けている。
public class RestClient {
/** HTTP Client */
protected final RestTemplate rest;
public RestClient() {
this( 60_000 ); // デフォルト60秒設定
}
/**
* @param timeout タイムアウト値(デフォルト60秒)
*/
public RestClient( int timeout ) {
this.rest = new RestTemplate();
// 3xx/4xx で例外を飛ばさないように、独自のエラーハンドラを差し込む。
this.rest.setErrorHandler( new QuietlyHandler() );
// PATCHでリクエストするためにリクエストファクトリーを設定。
// 後述pom.xmlへのhttpcomponents追加を忘れずに。
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setConnectTimeout( timeout );
requestFactory.setReadTimeout( timeout );
this.rest.setRequestFactory( requestFactory );
}
// RestTemplateを用いた移譲ユーティリティを実装(このGistでは省略)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment