目的
・Javaで実装された処理から、外部APIとHTTPでやり取りしたい
・bodyにXMLを詰めたい
・実装がなるべく簡単なものがいい
JavaのHTTPクライアントって・・・何を使ったらいいんだろう
ネット上の記事を参考に、
OkHttp(https://square.github.io/okhttp/)
というライブラリを使いました。
<!-- http client -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.7.0</version>
</dependency>
実装
例ではXMLをbodyに詰めてAPIをコールし、
APIから返却されるXMLのStringを受け取ってreturnします。
public String callSomething(String xml) throws IOException {
return new OkHttpClient().newCall(
new Request.Builder()
.url("【通信先URL】")
// basic authentication
.header("Authorization",
Credentials.basic(
"【basic認証user】",
"【basic認証password】"))
.post(RequestBody.create(MediaType.parse("text/xml"), xml))
.build()
).execute()
.body()
.string();
}
参考
JavaのHTTPクライアントはどれがいいのか?
https://qiita.com/alt_yamamoto/items/0d72276c80589493ceb4
追記(2019/08/13)
・都度newするのはよくなさげ
・環境によりタイムアウト時間等を適切に設定する必要性
という点を踏まえて修正しました。
@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class MyService {
private OkHttpClient client;
@PostConstruct
public void init() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(150, TimeUnit.SECONDS);
builder.readTimeout(150, TimeUnit.SECONDS);
builder.writeTimeout(150, TimeUnit.SECONDS);
client = builder.build();
}
public String callSomething(String xml) throws IOException {
try (Response res = client.newCall(
new Request.Builder()
.url("【通信先URL】")
.header("Authorization",
Credentials.basic(
"【basic認証user】",
"【basic認証password】"))
.post(RequestBody.create(MediaType.parse("text/xml"), xml))
.build()).execute()) {
return res.body().string();
}
}
}