-I want to communicate with an external API via HTTP from the process implemented in Java. ・ I want to pack XML in the body ・ I like something that is as easy to implement as possible.
Refer to the article on the net, OkHttp(https://square.github.io/okhttp/) I used a library called.
<!-- http client -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.7.0</version>
</dependency>
In the example, XML is packed in the body and the API is called. Receives the XML String returned from the API and returns.
public String callSomething(String xml) throws IOException {
return new OkHttpClient().newCall(
new Request.Builder()
.url("[Communication URL]")
// basic authentication
.header("Authorization",
Credentials.basic(
"[Basic authentication user]",
"[Basic authentication password]"))
.post(RequestBody.create(MediaType.parse("text/xml"), xml))
.build()
).execute()
.body()
.string();
}
Which Java HTTP client is better? https://qiita.com/alt_yamamoto/items/0d72276c80589493ceb4
・ It is not good to make new each time ・ It is necessary to set the timeout time appropriately depending on the environment. I corrected it based on that point.
@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("[Communication URL]")
.header("Authorization",
Credentials.basic(
"[Basic authentication user]",
"[Basic authentication password]"))
.post(RequestBody.create(MediaType.parse("text/xml"), xml))
.build()).execute()) {
return res.body().string();
}
}
}
Recommended Posts